Can't Log OKHTTP3 response.body.string - android

OK- so I'm a bit confused by this.
I've setup an OKHTTP3 POST. When I get the response I've been trying to put the body into a string (it's a string response) but something is going wonky:
try {
Response response = client.newCall(request).execute();
String rep = response.body().string();
if(rep.length() > 0){
Log.i(TAG, "Got Response");
Log.i(TAG, rep);
}
}catch (Exception e){
e.printStackTrace();
}
I get a Log saying "Got Response" but (the length is 80) then it just stops. It doesn't say my rep string is null, or empty... It just never calls that second Log.
Anyone have any kind of idea what's up?

I also met this problem, Log can't work.
And I found a temporary solution.
I try to use Toast to show the response, then I found that the response poped up, but with a lot of spaces(not sure if those characters are spaces).
So I am using Log.i(TAG, rep.trim());, which works well. I don't know if this solution is good for this problem, but it works for me after all.

Try using this..
OkHttpClient client = new OkHttpClient.Builder().build();
Request request = new Request.Builder()
.url("")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
Log.d("Response",response.body().string());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
response.body().close();
}
}
});

Right... So apparently I just needed to put the part that gets the string in an AsyncTask, and it started working.
There wasn't any error message or anything indicating to do so, but I went back and actually looked at the documentation for the Callback, and it mentions consuming the body on another thread.
new SendPictureClass().execute(response);
Probably should have started there to begin with... ¯_(ツ)_/¯
Thanks for the help guys!

Related

Android Okhttp Request Not Responding

I'm trying to Post JSON object in my application's login page. I searched for many examples and tried for them. But only my android 4.3 devices is running well and the other upper api level devices is not even response coming back. My code like below:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.LoginBtn:
loading.show();
try {
login();
} catch (JSONException e) {
e.printStackTrace();
}
break;
}
}
public void login(){
okhttp3.OkHttpClient client = new okhttp3.OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10,TimeUnit.SECONDS)
.readTimeout(10,TimeUnit.SECONDS)
.build();
final JSONObject JObje = new JSONObject();
try {
JObje.put("Username", String.valueOf(Username.getText()));
JObje.put("Password", String.valueOf(Password.getText()));
} catch (JSONException e) {
e.printStackTrace();
}
okhttp3.Request request = null;
okhttp3.RequestBody body = null;
body = new FormBody.Builder()
.addEncoded("JSONVALUE", String.valueOf(JObje))
.build();
request = new okhttp3.Request.Builder()
.url(context.getString(R.string.rutKontrolServis))
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.post(body)
.build();
client.newCall(request).enqueue(new okhttp3.Callback() {
#Override
public void onFailure(Call call, IOException e) {
}
#Override
public void onResponse(Call call, okhttp3.Response response) throws IOException {
Log.d("TAG","responded");
}
});
}
the R.string.rutKontrolServis url is like this: https://ourwebsite.com/folder/package_name.mywebservice
In my gradle file I added dependency this:
compile 'com.squareup.okhttp3:okhttp:3.11.0'
Is there any different request syntax or any constraint about tls or ssl certificates with newer api level devices? Can someone show a point
Did you try to increase the connection timeout and read timeout? I think 10 seconds is too short:
okhttp3.OkHttpClient client = new okhttp3.OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10,TimeUnit.SECONDS)
.readTimeout(10,TimeUnit.SECONDS)
.build();
Increase to 30 seconds and try again.
Sometimes OkHTTP just suddenly stops responding - no onFailure results, no onResponse results, even after increasing timeout. Nothing.
Switching your wifi / network provider to another provider worked for me.

Retrofit error message is broken

onResponse is called.
But response.isSuccessful() is false.
I want to watch error massage.
#Override
public void onResponse(Call<UserInfo> call, Response<UserInfo> response) {
if (!response.isSuccessful()) {
try {
Log.d("Success false", response.errorBody().string()); // letter broken!!
} catch (IOException e) {
e.printStackTrace();
}
return;
}
}
print :
{"error":"\ub85c\uadf8\uc778\uc774 \ud544\uc694\ud569\ub2c8\ub2e4."}
Why letter is broken?
I think the error message is UTF8 encoded string. You could decode it by URLDecoder.decode(s, s)
I fixed it!
I think of json data as a string data.
error massage is json data.
json data need convert.
Try this :
JSONObject jsonobject = new JSONObject ( response.errorBody().string());
Log.d("error",jsonobject.getString("error");

Retrofit GET for instagram access token. Getting 4xx but what am I missing?

https://www.instagram.com/developer/authentication/
Im on the last step (three). Im making a GET request and Im getting a response but it is now successful, im getting code 400 saying im missing client_id but I am not missing it. I saw a few others with the same problem but no clear solution. Below is the relevant code please have a look im a little bit new to retrofit.
//here I am creating the request to send through retrofit...
<!-- language: java -->
TokenRequest request = new TokenRequest();
request.setClient_id(Constants.CLIENT_ID);
request.setClient_secret(Constants.CLIENT_SECRET);
request.setGrant_type(Constants.AUTORISATION_CODE);
request.setRedirect_uri(Constants.REDIRECT_URI);
request.setCode(code);
//this is the actual request
final Call<TokenResponse> accessToken = ServiceManager.createTokenService().getAccessToken(request);
accessToken.enqueue(new Callback<TokenResponse>() {
#Override
public void onResponse(Call<TokenResponse> call, Response<TokenResponse> response) {
mtext.setText("hello");
if(response.isSuccess()){
mtext.setText("success");
}else{
try {
mtext.setText(response.errorBody().string());
//Log.d("mylog", response.errorBody().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}
At the moment its not going into the if block but showing the error in the else block.
I had my API interface built incorrectly, you can check the comments for the incorrect one. The correct one is the one below:
#FormUrlEncoded #POST("/oauth/access_token")
Call<TokenResponse> getAccessToken(#Field("client_id") String client_id,
#Field("client_secret") String client_secret,
#Field("redirect_uri") String redirect_uri,
#Field("grant_type") String grant_type, #Field("code") String code);
This was really tricky for me being new to retrofit hope it helps if you're stuck at the same problem!

Android Async Http Client

Hi i am using LoopJ lib to get response from server in json. But the problem is that at times i get org.apache.http.conn.ConnectTimeoutException and sometimes it runs fine. I am using the GET method. But when ever i copy and paste the URl to my Browser it runs fine But on the Android device i mostly cant connect to the server what is the problem. What am i doing wrong ?
client.setTimeout(timoutVal);
client.get(
"http://somewebsiteaddress.com/users.php?task=isUserPresent&email="
+ URLEncoder.encode(username) + "&password="
+ URLEncoder.encode(password) + "&licenseKey="
+ URLEncoder.encode(licKey), null,
new AsyncHttpResponseHandler() {
public void onSuccess(String response) {
loading.cancel();
Log.v("web response ", response);
try {
json = new JSONObject(response);
if (json.getBoolean("status")) {
delegate.Validation(
json.getBoolean("isUserPresent"),
json.getBoolean("license"), username,
password, json);
} else {
delegate.invalidLogin();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable arg) {
Log.v("onFailure", arg + "");
loading.cancel();
delegate.InternetErrorDialog();
super.onFailure(arg);
}
});
Try to increase your timeout value.
The reason is client will try to get response until timeout value.
As soon as it exceeds the timeout value it will throw timeout exception.

Response string is blank in loopj for Android

Here is the code that I have used for Async Http requests using loopj.
AsyncHttpClient loopjClient = new AsyncHttpClient();
PersistentCookieStore loopjCookieStore = new PersistentCookieStore(this);
loopjClient.setCookieStore(loopjCookieStore);
RequestParams loopjParams = new RequestParams();
loopjParams.put("username", username);
loopjParams.put("email", emailID);
loopjParams.put("password", password);
Log.d(TAG, "RRRRRRlll");
loopjClient.post("http://www.example.com/", loopjParams, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int k,String response) {
super.onSuccess(k, response);
Log.d(TAG, "RRRRRR "+ response );
}
});
And my server response string is just the following with out the HTML tags
{"AUTHENTICATION":{"SUCCESS":false,"USERNAME":"unregistered","USERID":0},"ALERTBOX":{"SHOW":true,"MESSAGE":"Message : Username or email ID already registered. Please choose a different one."}}
But loopj doesnt print the above string in onSuccess().
Can you tell how to get the string or do I have to fall back to default Android http library ?
Thanks in advance.
EDIT
Instead of 'example'(my site) if I replace it with 'facebook' I just get the following string as response with a 200 response code <?xml version="1.0" encoding="utf-8"?>
Since the result of AUTHENTICATION failed, I'm wondering if the status code that your server return is not 200. You can override onFailure method to deal with this situation.
#Override
public void onFailure(Throwable e) {
Log.d(TAG, e.toString());
}
Edit
Another guess, have you added the following line in your Manifest.xml?
<uses-permission android:name="android.permission.INTERNET" />
Edit Again
I saw your edit, and it seems that you have an buggy LogCat as #shailendra-rajawat mentioned in comment, since LogCat printed only the first line. Try Toast instead:
#Override
public void onSuccess(int k, String response) {
Toast.makeText(getBaseContext(), response, 1).show();
}
I found this post for configuring your LogCat, and maybe you can give it a try. (Mine is 5000 FYI)

Categories

Resources