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

38

我编写了一个简单的http请求/响应代码,但是我遇到了以下错误。 我在我的类路径中引用了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
3个回答

86

错误信息有些误导人。您提供的值并未代表完整的URI。

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

缺少协议。

只需提供完整的URI即可。

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

0
在我的情况下,我解决了在开头添加 / 的问题: request = new HttpGet("/trib.me/1lBFzSi");

0

这个错误可能是由于错误的URL引起的。 请检查以下URL:

  1. 协议缺失;
  2. URL参数编码;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接