org.apache.http.ProtocolException: Target host is not specified

时间秒杀一切 提交于 2020-01-30 04:06:32

问题


I have written a simple httprequest/response code and I am getting this below error. I have referenced httpclient, httpcore, common-codecs and common-logging in my classpath. I am very new to java and have no clue what is going on here. Please help me.

Code:

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.HttpResponse;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.Header;
import org.apache.http.HttpHeaders;

public class UnshorteningUrl {

    public static void main(String[] args) throws Exception
    {           
        HttpGet request=null;
        HttpClient client = HttpClientBuilder.create().build();         

        try {
            request = new HttpGet("trib.me/1lBFzSi");
            HttpResponse httpResponse=client.execute(request);

            Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION);
           // Preconditions.checkState(headers.length == 1);
            String newUrl = headers[0].getValue();          
            System.out.println("new url" + newUrl);         
        } catch (IllegalArgumentException e) {
            // TODO: handle exception
        }finally {
            if (request != null) {
                request.releaseConnection();
            }           
        }
    }}

Error:

Exception in thread "main" org.apache.http.client.ClientProtocolException
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:186)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:57)
    at UnshorteningUrl.main(UnshorteningUrl.java:26)
Caused by: org.apache.http.ProtocolException: Target host is not specified
    at org.apache.http.impl.conn.DefaultRoutePlanner.determineRoute(DefaultRoutePlanner.java:69)
    at org.apache.http.impl.client.InternalHttpClient.determineRoute(InternalHttpClient.java:124)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:183)
    ... 4 more

回答1:


The error message is kind of misleading. You've provided a value that does not represent a complete URI

request = new HttpGet("trib.me/1lBFzSi");

It's missing a protocol.

Simply provide a complete URI

request = new HttpGet("http://trib.me/1lBFzSi");



回答2:


This error is probably caused by the wrong url. Check the url:

  1. protocal missing;
  2. url parameters encode;


来源:https://stackoverflow.com/questions/24985771/org-apache-http-protocolexception-target-host-is-not-specified

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!