使用apache http客户端时java-未知主机异常

时间:2012-01-27 19:30:12

标签: java apache-httpcomponents

我正在尝试为网站提出一个简单的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);

1 个答案:

答案 0 :(得分:7)

看起来这里有一个简单的问题。

“HttpHost”对象的网址格式错误。您需要从“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.
}