sto usando okHttp 3.2.0 e qui è il codice per la costruzione di richiesta oggettocome ottenere corpo della risposta in okhttp quando il codice è 401
MediaType JSON = MediaType.parse(AppConstants.CONTENT_TYPE_VALUE_JSON);
RequestBody body = RequestBody.create(JSON, requestBody);
HttpUrl url = new HttpUrl.Builder()
.scheme("http")
.host("192.168.0.104")
.port(8080)
.addPathSegment("mutterfly-server")
.addPathSegment("j_spring_security_check")
.addQueryParameter("j_username", jsonObject.getString("emailId"))
.addQueryParameter("j_password", jsonObject.getString("password"))
.build();
request = new Request.Builder()
.addHeader(AppConstants.CONTENT_TYPE_LABEL, AppConstants.CONTENT_TYPE_VALUE_JSON)
.addHeader(AppConstants.ACCEPT_LABEL, AppConstants.CONTENT_TYPE_VALUE_JSON)
.url(url)
.post(body)
.build();
Ed ecco come ho analizzare la risposta
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
String respBody;
if (response.isSuccessful()) {
if (response.body() != null) {
respBody = response.body().string();
Log.i(TAG, respBody);
response.body().close();
if (AppMethods.checkIfNull(loginParserListener)) {
try {
final VUser user = AppMethods.getGsonInstance().fromJson(respBody, VUser.class);
} catch (Exception e) {
}
}
}
} else {
switch (response.code()){
case 401:
String body="HTTP_UNAUTHORIZED";
break;
}
}
}
});
Questa è la risposta ideale (dal client di riposo Web) quando l'autenticazione è fallita.
{"msgDesc":"The username or password you entered is incorrect..","statusCode":401}
EDIT:
response.toString()
rendimenti
Response{protocol=http/1.1, code=401, message=Unauthorized, url=http://192.168.0.104:8080/mutterfly-server/[email protected]&j_password=1}
response.body().toString()
restituisce
[email protected]
voglio prendere la 'msgDesc', che è nel corpo di risposta. c'è qualche metodo che restituirà questa stringa?
response.toString() restituisce Risposta {protocollo = http/1.1, codice = 401 , messaggio = Non autorizzato, url = http: //192.168.0.104: 8080/mutterfly-server/j_spring_security_check? [email protected]&j_password=1} –
Controlla la risposta aggiornata –
grazie per la risposta ma ho modificato il post con la risposta controllare che fuori –