2016-04-26 33 views
5

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?

risposta

5

Prova questo:

switch (response.code()){ 
     case 401: 
      JsonObject object=new JsonObject(response.body().string()); 
      String body=object.getString("msgDesc"); 
      break; 
} 
+0

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} –

+0

Controlla la risposta aggiornata –

+0

grazie per la risposta ma ho modificato il post con la risposta controllare che fuori –

-1

401 significa permission denied.

Verifica se il tuo token è valido o user/password è corretto.

+1

non v'è alcun gettone generato come sto provando a utenti registrati. e più su voglio testare il caso quando l'utente immette le credenziali sbagliate in modo da poter notificare all'utente con 'msgDesc' ricevuto dal server .. –

3

E 'abbastanza strano, ma Square, la società dietro OkHttp, ha scelto di non utilizzare 'toString()', ma 'stringa()' come metodo per ottenere il corpo come una stringa .

Quindi questo funziona;

String string = response.body().string(); 
//convert to JSON and get your value 

ma questo non significa:

String string = response.body().toString(); 
+1

sì, questa è la cosa strana. –

Problemi correlati