【问题标题】:java- unknown host exception when using apache http clientjava-使用apache http客户端时出现未知主机异常
【发布时间】:2012-01-27 19:30:11
【问题描述】:

我正在尝试对网站发出简单的 GET 请求,但我收到了未知的主机异常。

下面是我的代码--

     DefaultHttpClient client = new DefaultHttpClient();
     HttpHost targetHost=null;
     targetHost= new HttpHost("google.com/", 80, "http");
     HttpGet httpget = new HttpGet("about-us.html");
     BasicHttpContext localcontext = new BasicHttpContext();
     try {
        HttpResponse response = client.execute(targetHost, httpget, localcontext);

【问题讨论】:

  • 为什么主机名后面有斜线?

标签: java apache-httpcomponents


【解决方案1】:

看来你有一个简单的问题。

“HttpHost”对象的 URL 格式不正确。您需要从“google.com/”中删除“/”。 它应该在那之后工作。我使用您的代码进行了一次修改并且它有效。

DefaultHttpClient client = new DefaultHttpClient();
HttpHost targetHost = new HttpHost("google.com", 80, "http"); 
HttpGet httpget = new HttpGet("about-us.html");
BasicHttpContext localContext = new BasicHttpContext();
HttpResponse response = null;

try { response = client.execute(targetHost, httpget, localContext); 
      System.out.println(response.getStatusLine()
}
catch(Exception e){
    // Enter error-handling code here.
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-24
    • 1970-01-01
    相关资源
    最近更新 更多