Apache httpclient android 处理连接被拒绝

Apache httpclient android dealing with connection refused

我正在开发一个 intentservice,它将对服务器执行 httpget 并检索 json 字符串。

我正在使用以下代码,只要服务器启动它就可以工作:

 private String getServerContentsJson() throws IOException {
    HttpClient httpclient = new DefaultHttpClient();

   HttpResponse  response = httpclient.execute(new HttpGet(url));


    StatusLine statusline = response.getStatusLine();

    if(statusline.getStatusCode() == HttpStatus.SC_OK){

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        String responseString = out.toString();
        out.close();
        return responseString;}

    else{
        //Closes the connection.
        response.getEntity().getContent().close();
        throw new IOException(statusline.getReasonPhrase());

    }

问题是当服务器宕机时,我想妥善处理,但我不清楚如何处理。根据文档 httpclient.execute 将 return 一个正确的响应,或者抛出 IOException 或 ClientProtocolException,但我得到 HttpHostConnectException: Connection to http://irrelevantURL refused 似乎无法追溯到我的代码。然后应用程序崩溃。有什么建议吗?

这是完整的堆栈跟踪:

W/System.err﹕ org.apache.http.conn.HttpHostConnectException: Connection to http://irrelevantURL refused
W/System.err﹕ at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)
W/System.err﹕ at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
W/System.err﹕ at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
W/System.err﹕ at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)

编辑:我猜这与服务器关闭无关,而是它出于某种原因拒绝连接,问题仍然存在,但我仍然想妥善处理这个问题,这样应用程序就不会崩溃

HttpHostConnectExceptionIOException的一种,你没有处理好。你应该有类似下面的东西。如果 status_code 不是 200,您可能不想抛出异常,而是 return 一个有意义的错误 responseString

  private String getServerContentsJson()
    throws IOException {
    HttpClient httpclient = new DefaultHttpClient();

    String responseString = null;
    HttpResponse response = null;
    try {
      response = httpclient.execute(new HttpGet(url));

      StatusLine statusline = response.getStatusLine();

      if (statusline.getStatusCode() == HttpStatus.SC_OK) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        responseString = out.toString();
        out.close();
        return responseString;
      } else {
        responseString = statusline.getReasonPhrase();
      }
    } catch (IOException e) {
      throw new IOException(e.getMessage(), e);
      //OR:
      //responseString = "Could not reach server, please try again";
    } finally {
      if (response != null) {
        response.getEntity().consumeContent();
      }
    }
    return responseString;
  }