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

标签 java httpclient httpresponse apache-httpclient-4.x

我编写了一个简单的 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

最佳答案

该错误消息具有一定的误导性。您提供的值不代表完整的 URI

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

缺少协议(protocol)。

只需提供完整的 URI

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

关于java - org.apache.http.ProtocolException : Target host is not specified,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59819607/

相关文章:

java - 如何使用Java JSch库逐行读取远程文件?

java - 在 Activity 和 SDK [Android] 之间实现接口(interface)的最佳方式

java - 免费的 Restful api 可以用来练习吗?

c# - 使用 HttpClient 时如何在 HttpContent 中设置大字符串?

java - 这个方法是递归还是迭代?

httpclient - 请求重试 Apache HttpClient 之间的超时

wordpress - 修改 WordPress 中的 HTTP 响应 header

C# 在 MultiPart 响应内容到达时读取它们

c++ - 无法接收 HTTP 响应正文 C++

java - 套接字超时的junit测试用例