org.apache.http.ProtocolException: 未指定目标主机

我已经写了一个简单的httprequest/response代码,我得到了下面的错误。我已经在我的类路径中引用了httpclient,httpcore,common-codecs和common-logging。我对Java很陌生,不知道这里发生了什么。请帮帮我。

法典:

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();
            }           
        }
    }}

错误:

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

错误消息有点误导。您提供了一个不表示完整 URI 的值

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

它缺少一个协议。

只需提供完整的 URI

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

答案 2

此错误可能是由错误的网址引起的。检查网址:

  1. 原始缺失;
  2. 网址参数编码;

推荐