2

我正在尝试对网站发出简单的 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);
4

1 回答 1

7

看起来你在这里遇到了一个简单的问题。

您的“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.
}
于 2012-01-27T20:01:50.563 回答