HTTP请求json-android中的未知主机异常

时间:2010-09-13 07:02:33

标签: android json

我真的不知道为什么这个安卓代码不起作用..它显示未知的主机异常:

String requestTpServer = "www.google.com";
HttpClient client = new DefaultHttpClient();
HttpResponse response = null ;

try { 

  HttpGet get = new HttpGet(requestToServer);

  get.setHeader("Accept", "application/json");
  get.setHeader("content-type", "application/json");

  response = client.execute(getm);
  Log.i("Hit Success... in get deals response", "going to rendernow");

  if (response != null ) {
    Log.i("responsecode---", ""+response.getStatusLine().getStatusCode());
    String jsonResponseFromServer = response.toString();
    Log.i("json Response From Server", jsonResponseFromServer);
  }
  else {
   Log.i("blank ", "reply ");
  }
} catch (ClientProtocolException e) {

  e.printStackTrace();
} catch (IOException e) {

  e.printStackTrace();
}

String res = response.toString();
return res;

2 个答案:

答案 0 :(得分:2)

只是为了好奇:您是否尝试在网址前加上“http://”?

我正在使用以下帮助程序打开我的HTTP连接:

private InputStream openHttpConnection() throws IOException {
    InputStream in = null;
    int response = -1;

    URL url = new URL("http://www.myserver.com/someurl");
    URLConnection conn = url.openConnection();

    if (!(conn instanceof HttpURLConnection))
       throw new IOException("Not an HTTP connection");

    try {
       HttpURLConnection httpConn = (HttpURLConnection) conn;
       httpConn.setAllowUserInteraction(false);
       httpConn.setInstanceFollowRedirects(true);
       httpConn.setRequestMethod("GET");
       httpConn.connect();

       response = httpConn.getResponseCode();
       if (response == HttpURLConnection.HTTP_OK) {
          in = httpConn.getInputStream();
       }
    } catch (Exception ex) {
       throw new IOException("Error connecting");
    }
    return in;
}

也许这有帮助。

答案 1 :(得分:0)

当我落后于代理时,我得到了那个例外...... 因此,如果您支持代理,请联系管理员或在代码中提供代理设置。