I just got recently involved with android I have this code, I have it commented for some info.
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();
}
this works fine if I supply correct username and password but if not the http response code is 401
it throws an IOException
java.io.IOException: No authentication challenges found
and I couldn't get my response
this is my expected response when i get 401
{
"status": "error",
"message": "",
"data": [],
"status_code": 402
}
could anyone help me I have this task whole day and i couldn't seem to finish. any comment or suggestion would do. Thanks in advance