How to get response body in okhttp when code is 401? - android

I am using OkHttp 3.2.0 and here is code for building request object:
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();
And here is how I parse the response:
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;
}
}
}
});
This is the ideal response(from web rest client) when authentication is failed.
{"msgDesc":"The username or password you entered is incorrect..","statusCode":401}
EDIT:
response.toString() returns
Response{protocol=http/1.1, code=401, message=Unauthorized, url=http://192.168.0.104:8080/mutterfly-server/j_spring_security_check?j_username=s#s.s&j_password=1}
response.body().toString() returns
okhttp3.internal.http.RealResponseBody#528ae030
I want to fetch the msgDesc which is in response body. Is there any method which will return this string?

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

It's quite weird but Square, the company behind OkHttp, has chosen to not use 'toString()' but 'string()' as method for getting the body as a String.
So this works;
String string = response.body().string();
//convert to JSON and get your value
But this doesn't:
String string = response.body().toString();

401 means permission denied.
Check if your token is valid or user/password is correct.

Related

Value of type java.lang.String cannot be converted to JSONObject when passing http response

Im getting the "Value of type java.lang.String cannot be converted to JSONObject" error when trying to pass the response string to the JSON object. I've tried something similar in the past, and it worked, so I have no idea why it's happening.
Here's the code
public void searchMovie(){
OkHttpClient client = new OkHttpClient();
url = Constants.moviebaseurl + mEdit.getText();
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NotNull Call call, #NotNull IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException {
final String myResponse = response.body().toString();
SearchActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONObject json = new JSONObject(myResponse);
JSONArray results = json.getJSONArray("results");
mText.setText(results.getJSONObject(0).getString("title"));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
Am I doing something wrong, or am I just missing something? Thank you for your help!
It worked changing
final String myResponse = response.body().toString();
for
final String myResponse = response.body().string();
From referencing this question I was able to find this answer
Using google-gson you can do it like this:
JsonObject obj = new JsonParser().parse(myResponse).getAsJsonObject();
This question itself might even lead to some insight of the issue if my code doesn't work for you.

Separate Class for OkHttp Requests

I use OkHttp for requests to my raspberry. I am thinking about putting the requests in a separate class.
Currently I have one method to send requests. The code is as follows:
private void sendRequest(String url, JSONObject json) {
Log.d(TAG, "sendRequest: Das Json: " + json);
// Authentication for the request to raspberry
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.authenticator(new Authenticator() {
#Override
public Request authenticate(Route route, Response response) throws IOException {
String credential = Credentials.basic("username", "password");
return response.request().newBuilder()
.header("Authorization", credential)
.build();
}
});
// Sending out the request to the raspberry
OkHttpClient okHttpClient = client.build();
RequestBody body = RequestBody.create(null, new byte[]{});
if( json != null) {
body = RequestBody.create(MediaType.parse(
"application/json"),
json.toString()
);
}
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.d(LOG, "Big Fail");
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
ResponseBody responseBody = response.body();
if( !response.isSuccessful() ) {
Log.d(TAG, "onResponse: We are in !response.successful()");
throw new IOException("Response not successful: " + response );
}
Log.d(LOG, "onResponse: Response is: " + responseBody.string());
} catch (Exception e) {
e.printStackTrace();
Log.d(LOG, "onResponse: failed!" + e);
}
}
});
}
Here is an example how the sendRequest() function is called:
private void makePremixCall(Premix premix) {
JSONArray jsonArray = new JSONArray();
ArrayList<Premixable> usedPremixables = premix.getUsedPremixables();
for(Premixable usedPremixable: usedPremixables) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("Silo", usedPremixable.getmSilo());
jsonObject.put("Gramm", usedPremixable.getmKgPerCow() * mFeeding.getmNumberOfCows());
jsonArray.put(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("Components", jsonArray);
sendRequest("http://192.168.178.49:5000/evaluatePost", jsonObject);
} catch (JSONException e) {
e.printStackTrace();
Log.d(TAG, "makePremixCall: " + e);
}
}
My problem with this: I would like to have a separate class, which offers the function makePremix(Premix premix) and other functions that I need.
The only solution that comes to my mind is implementing the requests synchronously in the separate class and call that separate class in an AsyncTask in the class I am working in.
Do I oversee something? Is there a way to create a separate class and still use the OkHttp enqueue method?
You could extract makePremix(Premix premix) in a separate class and make sendRequest() public (or maybe package-private depending on your use case).
public void sendRequest(String url, JSONObject json)
However since sendRequest is generic and can be used by any other makeAnotherCall() in some other class you would need to get back result of every requests. Hence you can extract the Callback out of sendRequest()
public void sendRequest(String url, JSONObject json, Callback callback)
Now your sendRequest will look like
private void sendRequest(String url, JSONObject json) {
Log.d(TAG, "sendRequest: Das Json: " + json);
// Authentication for the request to raspberry
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.authenticator(new Authenticator() {
#Override
public Request authenticate(Route route, Response response) throws IOException {
String credential = Credentials.basic("username", "password");
return response.request().newBuilder()
.header("Authorization", credential)
.build();
}
});
// Sending out the request to the raspberry
OkHttpClient okHttpClient = client.build();
RequestBody body = RequestBody.create(null, new byte[]{});
if( json != null) {
body = RequestBody.create(MediaType.parse(
"application/json"),
json.toString()
);
}
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
okHttpClient.newCall(request).enqueue(callback);
}
Hope it makes sense!
Also as a side note, see that you are creating a new OkHttp Client every time you call sendRequest. You could probably optimise memory here by caching the client and reusing it.

okhttp get failure response

I've implemented okhttp in my android client for network calls.
When i get a failure response i get the failure code and the text related to the code as a message but i don't get the custom failure response that the server sends me.
In my failure response in the implemented code the message i get is just "Bad Request".
Whereas the same response from the browser is as follows.
How do i get the error message the server is giving me back?
My code
private void executeCall(Request request, final ResponseListener listener) {
mOKHttpClient.newCall(request)
.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
postFailure(listener, (String) call.request()
.tag(),e.toString());
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
if(response.isSuccessful()) {
String responseString = response.body().string();
postSuccess(listener, (String)call.request().tag(), responseString);
}
else {
postFailure(listener, (String)call.request().tag(),response.code()+","+response.message());
}
}
});
}
Here's my response in case of failure.
You will have to catch error response by body() because response.message() returns HTTP status message.
In the screen shot provided by you:
Status is broken down in OkHttp like response.code() for HTTP status code which is 400 in your case and response.message() for HTTP status message which is Bad Request in your case.
The body of the response (be it success or failure) is response.body(). And if you want to get it as a String, then call response.body().string().
#Override
public void onResponse(Call call, final Response response) throws IOException {
if(response.isSuccessful()) {
String responseString = response.body().string();
postSuccess(listener, (String)call.request().tag(), responseString);
}
else {
String errorBodyString = response.body().string();
postFailure(listener, (String)call.request().tag(),response.code()+","+errorBodyString);
}
}
As per comments:
Since you want to read Message object from the response, try to do like this:
JSONObject object = new JSONObject (response.body().string());
String messageString = object.getString("Message");
if you are trying to get (okhttp3.ResponseBody) errorResponse from Retrofit response do this..
// Retrofit onResponseCall
#Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
if (response.errorBody() != null) {
try {
Log.e("errorResponse","" + response.errorBody().toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}

PUT failing on OKHTTP

I am using okHTTP in Android to make a PUT request. I Have added the headers and I have added .put request. But somehow the request is not going through. I have used Log entries to trace that. The code goes like:
String url = "http://xxxxxxxxxx.com/v1.0/xxxxxx/" + xxxxxxx;
JSONObject jSon = new JSONObject();
try {
jSon.put("prescription_interval_id", prescriptionIntervalId);
} catch (JSONException e) {
e.printStackTrace();
}
try {
jSon.put("prescription_auto_refill", false);
} catch (JSONException e) {
e.printStackTrace();
}
String data = jSon.toString();
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, data);
Request request = new Request.Builder()
.url(url)
.addHeader("Authorization", token)
.addHeader("Content-Type", "application/json")
.put(body)
.build();
//
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
Log.d("FAIL","CALL FAILED");
Log.d("Request",request.toString());
}
#Override
public void onResponse(Response response) throws IOException {
Log.d("Response",response.toString());
Log.d("SUCCESS","CALL SUCCEEDED");
}
});
The request is not being made. I don't know why.
Oh! Accidentally i was putting a space in between url end points! works fine now :)

Retrofit 2 - null response body

I am trying to convert following response with Retrofit 2
{
"errorNumber":4,
"status":0,
"message":"G\u00f6nderilen de\u011ferler kontrol edilmeli",
"validate":[
"Daha \u00f6nceden bu email ile kay\u0131t olunmu\u015f. L\u00fctfen giri\u015f yapmay\u0131 deneyiniz."
]
}
But I am allways getting null response in onResponse method. So I tried to look at error body of the response with response.errorBody.string(). Error body contains exactly same content with raw response.
Here is my service method, Retrofit object and response data declerations:
#FormUrlEncoded
#POST("/Register")
#Headers("Content-Type: application/x-www-form-urlencoded")
Call<RegisterResponse> register(
#Field("fullName") String fullName,
#Field("email") String email,
#Field("password") String password);
public class RegisterResponse {
public int status;
public String message;
public int errorNumber;
public List<String> validate;
}
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
final String content = UtilityMethods.convertResponseToString(response);
Log.d(TAG, lastCalledMethodName + " - " + content);
return response.newBuilder().body(ResponseBody.create(response.body().contentType(), content)).build();
}
});
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
domainSearchWebServices = retrofit.create(DomainSearchWebServices.class);
I have controlled response JSON with jsonschema2pojo to see if I modled my response class wright and it seems OK.
Why Retrofit fails to convert my response?
UPDATE
For now as a work around I am building my response from error body.
I have solved the problem. When I make a bad request (HTTP 400) Retrofit doesn't convert the response. In this case you can access the raw response with response.errorBody.string(). After that you can create a new Gson and convert it manually:
if (response.code() == 400 ) {
Log.d(TAG, "onResponse - Status : " + response.code());
Gson gson = new Gson();
TypeAdapter<RegisterResponse> adapter = gson.getAdapter(RegisterResponse.class);
try {
if (response.errorBody() != null)
registerResponse =
adapter.fromJson(
response.errorBody().string());
} catch (IOException e) {
e.printStackTrace();
}
}

Categories

Resources