本文介绍了org.apache.http.ProtocolException:未指定目标主机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个简单的 httprequest/response 代码,但出现以下错误.我在我的类路径中引用了 httpclient、httpcore、common-codecs 和 common-logging.我对java很陌生,不知道这里发生了什么.请帮我.

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.

代码:

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

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");

缺少协议.

只需提供一个完整的 URI

Simply provide a complete URI

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

这篇关于org.apache.http.ProtocolException:未指定目标主机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 04:41