I'm trying to do a digest authentication to this server http://52.16.207.138/api/v0.1/device/999 user = 5588031263bf4457a7641c07 and pass = 5588031263bf4457a7641c08 over web browser, i get a 200 http code and a json of some status.
My android code:
private JSONObject POST() throws JSONException {
JSONObject response = null;
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("5588031263bf4457a7641c07", "5588031263bf4457a7641c08".toCharArray());
}
});
try {
URL url1 = new URL("http://52.16.207.138/api/v0.1/device/999");
HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
conn.setRequestMethod(GET);
conn.connect();
int status = conn.getResponseCode();
InputStream is;
if(status >= HttpURLConnection.HTTP_BAD_REQUEST)
is = conn.getErrorStream();
else
is = conn.getInputStream();
Log.d("RespuestaHTTP",String.valueOf(status));
byte[] buffer = new byte[8196];
int readCount;
StringBuilder builder = new StringBuilder();
while ((readCount = is.read(buffer)) > -1) {
builder.append(new String(buffer, 0, readCount));
}
response = new JSONObject(builder.toString());
Log.d("Respuesta",response.toString());
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
But I always get 401 response, and I don't know what i'm doing bad.
Someone can help me???
06-22 18:57:17.797 1708-1750/com.example.urbanclouds.pruebasdigest D/RespuestaHTTP﹕ 401
Copied my answer to another HTTP digest question:
HttpUrlConnection
does not support Digest authentication. If your client must authenticate using Digest, you have a few options:HttpURLConnection
.okhttp-digest
as an authenticator and you will have transparent Http digest support. If you already use OkHttp or are OK with switching to it this can be an attractive option.HttpClient
which supports Digest. This option is included mostly for completion's sake since Google does not recommend usingHttpClient
and has deprecated it.