我刚刚参与了android我有这个代码,我已经评论了一些信息。
HttpURLConnection con = null;
String token = null;
String message = null;
try {
con = (HttpURLConnection)new URL(Constants.URL_LOGIN + deviceID).openConnection();
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
DataOutputStream dos = new DataOutputStream(con.getOutputStream());
System.out.println("pin wala" + username + password + pincode);
dos.write((Constants.JSON_LOGIN_USERNAME + "=" + username + "&" + Constants.JSON_LOGIN_PASSWORD + "=" + password).getBytes(Charset.forName("UTF-8")));
dos.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder jsonStringBuilder = new StringBuilder();
String s = null;
while((s = reader.readLine()) != null) {
jsonStringBuilder.append(s);
System.out.println(s);
}
reader.close();
JSONObject jsonLogin = new JSONObject(jsonStringBuilder.toString());
if(jsonLogin != null) {
//here, should go the the return
//if statuscode is 401 i have this mystatus to be setted if not the api call is successful
if(jsonLogin.getInt("mystatus") == 402){
MainActivity.this.forPincode = true;
} else {
// no problem here this is successful api call
}
}
} catch(MalformedURLException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch(JSONException e){
e.printStackTrace();
}
finally {
if(con != null)
con.disconnect();
}
如果我提供正确的用户名和密码,这样可以正常工作但如果不是http响应代码401
则会引发IOException
java.io.IOException: No authentication challenges found
而我无法得到我的回复< / p>
这是我得到401时的预期回应
{
"status": "error",
"message": "",
"data": [],
"status_code": 402
}
谁能帮助我,我整天都有这项任务,而且我似乎无法完成任务。任何评论或建议都可以。提前致谢
答案 0 :(得分:2)
con.getInputStream()仅在Http返回介于200和299之间的代码时才有效。对于任何其他响应代码,请使用con.getErrorStream()。
你应该看起来像这样:
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getResponseCode() / 100 == 2 ? con.getInputStream() : con.getErrorStream()));