これは私の状況です。私は、POSTのメッセージでWeb認証APIを呼び出しています。成功すると、トークンを返します。それ以外の場合は、理由コード(例:"incorrect password", "account lock", etc
)と応答コード400, etc
を指定してエラーメッセージ(json)を返します。ブラウザから見Java AndroidどのようにExceptionでHTTPUrlConnection(POST)レスポンスコードとメッセージを取得するのですか?
サンプルエラー:
ので、エラーが発生した場合、私はコールに管理し、成功メッセージを取得し、を返しますが、ありません。ここでは擬似コードだ(私は冗長な部分を省く基本的には「キャッチ」スコープに焦点を当てています。):
HttpURLConnection conn = null; //Must define outside as null?
try {
...
byte[] postDataBytes = ...
URL url = new URL(urlLogin);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
...
conn.getOutputStream().write(postDataBytes);
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder();
for (int c; (c = in.read()) >= 0;)
sb.append((char)c);
String response = sb.toString(); // Yeah I got this
return response;
}
catch(IOException ex){
//the variable ex doesn't tell anything about the response code
//neither the response message
//so i access the conn to get
//
try {
int responseCode = conn.getResponseCode();
return "code: " + responseCode; //somehow this line just doesn't work!
}
catch (Exception ex2){
}
}
ビットを詳述すると、IOException
は応答については何も教えてくれありません。だから私はHttpURLConnection
変数にアクセスします。
conn.getResponseCode() does return 400
、
conn.getResponseMessage() does return "Bad Request"
ではなく、サーバーからのエラーJSONメッセージ。
EDIT:
私はちょうど例外/エラー時の応答コード/メッセージを取得するための正しい方法は何か、知りたいです。
あなたが使用することができます[getErrorStream()](https://developer.android.com/reference/java/net/HttpURLConnection.html#getErrorStream())HttpURLConnectionのの。 – Geros
あなたが言ったようにjsonのテキストが返されるので、キャッチはありません。 – greenapps