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 以外のクラスを使用する必要がありますか?