【发布时间】:2013-01-28 22:04:39
【问题描述】:
在 AsyncTask 的“doInBackground”函数中,我得到以下代码:
try
{
URL url = new URL(myUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
Authenticator.setDefault(new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication ("myUsername", "myPassword".toCharArray());
}
});
conn.connect();
int response = conn.getResponseCode();
inputStream = conn.getInputStream();
String content = convertInputStreamToString(inputStream);
return content;
catch (Exception e) {
e.printStackTrace();
return null;
}
当凭据正常时,一切正常并且 ResponseCode 为 200。但如果我输入了错误的凭据,getResponseCode() 会使 AsyncTask 无限期地等待答案(超时不起作用)。查看 HttpUrlConnection 对象告诉我 ResponseCode 是 -1。
我需要处理所有情况,即使用户提供了错误的凭据。我怎样才能得到一个有用的答案?我应该使用 HttpUrlConnection 以外的其他类吗?
【问题讨论】:
-
你没有对超时异常做任何事情。
-
我刚刚更新了我的问题以添加我正在做的 try/catch。捕获永远不会被调用。
标签: java android http httpurlconnection