我正在开发一个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
将返回正确的响应,或者抛出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)
编辑:我想这与服务器关闭无关,但由于某种原因拒绝连接,问题仍然存在,但我仍然想要正确处理这个问题,以便应用程序不会崩溃
答案 0 :(得分:2)
HttpHostConnectException
是一种IOException
,您没有正确处理它。你应该有类似下面的东西。如果status_code
不是200,您可能不想抛出异常,而是返回有意义的错误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;
}