gpt4 book ai didi

java - Apache httpclient android 处理连接被拒绝

转载 作者:行者123 更新时间:2023-12-02 04:51:12 25 4
gpt4 key购买 nike

我正在开发一个 Intent 服务,它将对服务器执行 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 returned这似乎无法追溯到我的代码。然后应用程序崩溃。有什么建议吗?

这是完整的堆栈跟踪:

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)

编辑:我想这与服务器关闭无关,而是由于某种原因拒绝连接,问题仍然存在,但我仍然想正确处理这个问题,以便应用程序不会崩溃

最佳答案

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;
}

关于java - Apache httpclient android 处理连接被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29220405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com