Below are the files for retrofit.
While passing the data in the form of JSON I am getting a null response.
Could anyone guide where can be the issue occurring?
I am trying to post the data in the form of JSON using the retrofit library. Can you suggest me the right approach?
My code:
public class ApiSellarClient {
public static final String BASE_URL = "Constant.BASE_URL";// it is from constant file..
private static Retrofit retrofit = null;
public static Retrofit getClient() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
public class ApiSellarConnection {
public static Call<String> getSignInData(JSONObject json) {
return ApiSellarClient.getClient().create(ApiSellarInterface.class).getSignInData(json);
}
}
public interface ApiSellarInterface {
#Headers("Content-Type: application/json")
#POST("integration/customer/token")
Call<String> getSignInData(#Body JSONObject json);
}
// Below is the controller class.
JSONObject paramObject = new JSONObject();
try {
paramObject.put("username", etUserName.getText().toString());
paramObject.put("password", etPassword.getText().toString());
ApiSellarConnection.getSignInData(paramObject).enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
Log.d("tag", "helper" + response.body());
}
#Override
public void onFailure(Call<String> call, Throwable t) {
}
});
} catch (JSONException e) {
e.printStackTrace();
}
I tried send json-rpc via retrofit2.
This is my interface:
public interface ApiInterfaceJson {
#POST
#Headers( "Content-Type: application/json" )
Call<String> getDataJson(
#Url String url,
#Body RequestBody body);
}
Create retrofit:
retrofitJson = new Retrofit.Builder()
.addConverterFactory(ScalarsConverterFactory.create())
.baseUrl("http://localhost:8800")
.client(client)
.build();
apiInterfaceJson = retrofitJson.create(ApiInterfaceJson.class);
Call:
JSONObject paramObject = new JSONObject();
try {
paramObject.put("id", "0");
paramObject.put("name", "user");
paramObject.put("command", "finish");
}catch(Exception e){
}
RequestBody requestBody= RequestBody.create(MediaType.parse("application/json"), paramObject.toString());
MinersMonitorApplication.getApiJson().getDataJson("http://10.10.10.230:10000", requestBody).enqueue(new Callback<String>() {
#Override
public void onResponse(#NonNull Call<String> call, #NonNull Response<String> response) {}
#Override
public void onFailure(Call<String> call, Throwable t) {
}
});
The result is SocketTimeoutException.
You need RPC wrapped retrofit - https://github.com/segmentio/retrofit-jsonrpc
Also let service see that it should use json RPC by annotating:
interface MultiplicationService {
#JsonRPC("Arith.Multiply") #POST("/rpc")
Call<Integer> multiply(#Body MultiplicationArgs args);
}
Note that Retrofit is only REST Based library.
When I use JsonObject as response in retrofit my output is: response: {}
Here is my code with JsonObject response:
mCall=apiService.Check_App_Version("api/check-app-version/1/"+Utility.Get_App_Version(context));
mCall.enqueue(new Callback<JSONObject>() {
#Override
public void onResponse(Call<JSONObject> call, Response<JSONObject> response) {
Log.e("response",""+response.body().toString()+" "+response.code());
}
#Override
public void onFailure(Call<JSONObject> call, Throwable t) {
Log.e("ERROR",t.toString());
}
});
But when I use Object as the response in retrofit my output is:
response: {data=[{result=1.0, is_necessary=0.0}]}
and here is code for this:
mCall=apiService.Check_App_Version("api/check-app-version/1/"+Utility.Get_App_Version(context));
mCall.enqueue(new Callback<Object>() {
#Override
public void onResponse(Call<Object> call, Response<Object> response) {
Log.e("response",""+response.body().toString()+" "+response.code());
}
#Override
public void onFailure(Call<Object> call, Throwable t) {
Log.e("ERROR",t.toString());
}
});
I want to use it as JsonObject. where is my mistake?
Please use GsonConverterFactory to get parsed response in your desired object and if you want String response with Retrofit, use ScalarsConverterFactory. You can add both factories at the same time.
OkHttpClient client = new OkHttpClient.Builder().connectTimeout(3, TimeUnit.MINUTES)
.writeTimeout(3, TimeUnit.MINUTES)
.readTimeout(3, TimeUnit.MINUTES).addInterceptor(interceptor).build();
if (retrofit == null) {
String baseUrl = "http://example.com/";
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.addConverterFactory(ScalarsConverterFactory.create())
.client(client)
.build();
}
I'm upgrading retrofit 1.9 to v2.1.0. I want to get the response json and convert it manually but I got something like this:
log res retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall#41acd528-okhttp3.ResponseBody$1#41ad8a18
my code is :
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
client = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.addInterceptor(logging)
.build();
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.baseUrl(Config.baseEndpoint)
.build();
ApiService api = retrofit.create(ApiService.class);
Call<ResponseBody> login = api.login("email", "password");
login.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.e(TAG, "log res "+call.toString()+"-"+response.body().toString());
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
use JsonObject instead of ResponseBody
Call<JsonObject> login = api.login("email", "password");
login.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
Log.e(TAG, "log res "+call.toString()+"-"+response.body().toString());
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
}
});
Note : make sure to use com.google.gson.JsonObject, not org.json.JSONObject
Logcat Snapshot
Good Evening,
I'm using Retrofit2 to make a POST request using the following dependencies
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'
compile 'com.google.code.gson:gson:2.7'
Now the problem I'm facing is that the response with the HttpLoggingInterceptor is correct but Response Body is empty.
Here's my code
Retrofit2 Setup
public Retrofit setUpRetrofit(){
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.create();
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(logging);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(httpClient.build())
.build();
return retrofit;
}
API
#POST("hngeCommerceWebservice/rest/product/categoryNew/")
Call<Data> getData(#Body UserData userData);
MainActivity:
Call<Data> dataCall = api.getData(userData);
dataCall.enqueue(new Callback<Data>() {
#Override
public void onResponse(Call<Data> call, Response<Data> response) {
int statusCode = response.code();
Log.d(TAG, response.toString() + " STRING");
Log.d(TAG, response.body().getSkuItems()+ " BODY");
Log.d(TAG, response.raw() + " RAW");
Log.d(TAG, response.message().toString());
Log.w("Response ",new Gson().toJson(response));
}
#Override
public void onFailure(Call<Data> call, Throwable t) {
Log.d(TAG, "onFailure: " + t.getMessage() + "");
}
});
This is the Response by Log.w("Response ",new Gson().toJson(response));
{"body":{"brandFilterdata":[],"priceFilterData":[],"skuItems":[],"validCouponCode":false},"rawResponse":{"body":{"contentLength":-1,"contentType":{"mediaType":"application/json","subtype":"json","type":"application"}},"code":200,"headers":{"namesAndValues":["Server","Apache-Coyote/1.1","Content-Type","application/json","Transfer-Encoding","chunked","Date","Thu, 15 Sep 2016 19:14:36 GMT"]},"message":"OK","networkResponse":{"code":200,"headers":{"namesAndValues":["Server","Apache-Coyote/1.1","Content-Type","application/json","Transfer-Encoding","chunked","Date","Thu, 15 Sep 2016 19:14:36 GMT"]},"message":"OK","protocol":"HTTP_1_1","receivedResponseAtMillis":1473966805216,"request":{"cacheControl":{"isPrivate":false,"isPublic":false,"maxAgeSeconds":-1,"maxStaleSeconds":-1,"minFreshSeconds":-1,"mustRevalidate":false,"noCache":false,"noStore":false,"noTransform":false,"onlyIfCached":false,"sMaxAgeSeconds":-1},"headers":{"namesAndValues":["Content-Type","application/json; charset\u003dUTF-8","Content-Length","235","Host","119.81.82.197:9090","Connection","Keep-Alive","Accept-Encoding","gzip","User-Agent","okhttp/3.3.1"]},"method":"POST","tag":{"headers":{"namesAndValues":[]},"method":"POST","url":{"host":"119.81.82.197","password":"","pathSegments":["hngeCommerceWebservice","rest","product","categoryNew",""],"port":9090,"scheme":"http","url":"http://119.81.82.197:9090/hngeCommerceWebservice/rest/product/categoryNew/","username":""}},"url":{"host":"119.81.82.197","password":"","pathSegments":["hngeCommerceWebservice","rest","product","categoryNew",""],"port":9090,"scheme":"http","url":"http://119.81.82.197:9090/hngeCommerceWebservice/rest/product/categoryNew/","username":""}},"sentRequestAtMillis":1473966804371},"protocol":"HTTP_1_1","receivedResponseAtMillis":1473966805216,"request":{"headers":{"namesAndValues":["Content-Type","application/json; charset\u003dUTF-8","Content-Length","235"]},"method":"POST","tag":{"headers":{"namesAndValues":[]},"method":"POST","url":{"host":"119.81.82.197","password":"","pathSegments":["hngeCommerceWebservice","rest","product","categoryNew",""],"port":9090,"scheme":"http","url":"http://119.81.82.197:9090/hngeCommerceWebservice/rest/product/categoryNew/","username":""}},"url":{"host":"119.81.82.197","password":"","pathSegments":["hngeCommerceWebservice","rest","product","categoryNew",""],"port":9090,"scheme":"http","url":"http://119.81.82.197:9090/hngeCommerceWebservice/rest/product/categoryNew/","username":""}},"sentRequestAtMillis":1473966804371}}
But Correct response with HttpLoggingInterceptor