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.
Related
I use Retrofit2 to call api, when I do apiTest("http://xxx.xx.xx.xxx:xxxx/", "T001", "Futek10911-01"), the response.code is 999 but it returns correct value in Postman. Where's the problem?
private void apiTest(String url, String machId, String check) throws JSONException {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
MyAPIService myAPIService = retrofit.create(MyAPIService.class);
JSONObject jsonObject = new JSONObject();
jsonObject.put("MACHID", machId);
jsonObject.put("CHECK", check);
Call<GetHostTime> call = myAPIService.getHostTime("sRequest", jsonObject);
call.enqueue(new Callback<GetHostTime>() {
#Override
public void onResponse(Call<GetHostTime> call, Response<GetHostTime> response) {
if(response.isSuccessful()){
Log.d("response ", "isSuccessful");
}else {
Log.d("response code ", response.code() + "");
}
}
#Override
public void onFailure(Call<GetHostTime> call, Throwable t) {
Log.d("Failure", t.getMessage());
}
});
public interface MyAPIService {
#POST("TcLeaseParkAPI/api/ParkingAPI/GetHostTime")
#FormUrlEncoded
Call<GetHostTime> getHostTime(#Field("MACHID") String key, #Field("CHECK") JSONObject jsonObject);
}
Comparing your Postman request and your code. It is clear I feel you are sending the request in wrong manner.
So we modify your Retrofit request as follows
public interface MyAPIService {
#POST("TcLeaseParkAPI/api/ParkingAPI/GetHostTime")
#FormUrlEncoded
Call<GetHostTime> getHostTime(#Field("sRequest") JSONObject jsonObject);
And then your request Call as follows
Call<GetHostTime> call = myAPIService.getHostTime(jsonObject);
Now your JSONObject will go in the key sRequest
Step1:
Need to give input to server.as below image
step2:
get response from server ,as below image.
![enter image description here][2]
step3:
MainActivity.java
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiInterface.URL_BASE)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
// prepare call in Retrofit 2.0
try {
JSONObject paramObject = new JSONObject();
paramObject.put("merchant_id", "aaaaa");
paramObject.put("secret_key", "bbbbb");
Call<RequestBody> userCall = apiInterface.getUser(paramObject.toString());
userCall.enqueue(this);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onResponse(Call<RequestBody> call, Response<RequestBody> response) {
Log.d("TEST","TEST--onResponse1---"+call);
Log.d("TEST","TEST--onResponse2---"+response);
}
#Override
public void onFailure(Call<RequestBody> call, Throwable t) {
Log.d("TEST","TEST--onFailure1--"+call);
Log.d("TEST","TEST--onFailure1--"+t);
}
========================================================
step4: ApiInterface.hava
public interface ApiInterface {
#Headers("Content-Type: application/json")
Call<RequestBody> getUser(#Body String body);
}
Log is going to "onResponse.code()" is getting 307" but i count able
to get proper data.
I am new to Retrofit service.Can please help me.
You can't send String to Retrofit without using some other library.
Since you're using Gson already. Create a class that Gson can serialize.
class Credentials {
#SerializedName("merchant_id")
public String merchantId;
#SerializedName("secret_key")
public String secretKey;
}
Interface method. #Notice the input type.
#Headers("Content-Type: application/json")
Call<RequestBody> getUser(#Body Credentials credentials);
307 is Temporary Redirect - and you might have to follow that redirect.
Which means, that you need to configure the OkHttpClient to do so:
OkHttpClient client = new OkHttpClient.Builder()
.followSslRedirects(true)
.followRedirects(true)
.build();
and then set it as the client for retrofit2:
retrofit = new retrofit2.Retrofit.Builder()
.baseUrl(Constants.API_BASE_URL)
.client(client)
.build();
I have a problem in using retrofit. I have a API https://raakar.ir/addProject and want to send some information. API works fine in postman. I want to make post request. I think, I do every think correctly. But when I run the app, It crash.
I used these libraries:
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
and these are my interface of retrofit :
public interface APIInterface {
#Multipart
#POST("addProject")
Call<AddProjectResponse> post(
#Header("token") String token,
#Field("name") String name,
#Field("amount") String amount,
#Field("description") String description,
#Field("category") String category,
#Field("deadline") String deadline,
#Field("projectFile")Bitmap bitmap
);
}
------------------------------------------------------------------------------------------------------------------------------------
Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl("https://raakar.ir/")
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
APIinterface retroInterface = retrofit.create(APIinterface.class);
Call<AddProjectResponse> call = retroInterface.post(token,
"طراحی راکار",
"50000000",
"خالی است",
"برنامه نویسی",
"5",
null);
call.enqueue(new Callback<AddProjectResponse>() {
#Override
public void onResponse(Call<AddProjectResponse> call, Response<AddProjectResponse> response) {
Log.d("Resposne:", response.toString());
}
#Override
public void onFailure(Call<AddProjectResponse> call, Throwable t) {
Log.d("Respone:", "Error");
}
});
PLEASE HELP me!
i thing if you are not post any image and other file like video etc then you can not used #Multipart and also pass in post method paremater make one pojo class for that and only pass your object like below that...sample code
MyEventRequestModel myEventListRequestModel = new MyEventRequestModel(); // define your pojo class object
myEventListRequestModel.setDate(mDate);
Call<MyEventResponseModel> call = apiInterface.getAllEvent(myEventListRequestModel);
and header will be set on retrofit intialized..
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.readTimeout(60, TimeUnit.SECONDS);
client.writeTimeout(60, TimeUnit.SECONDS);
client.connectTimeout(60, TimeUnit.SECONDS);
client.addInterceptor(interceptor);
client.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (context == null) {
request = request
.newBuilder()
.build();
} else {
request = request
.newBuilder()
.addHeader("Authorization", "Bearer " + AppSetting.getStringSharedPref(context, Constants.USER_KEY_TOKEN, "")) // hear define your header.
.build();
}
return chain.proceed(request);
}
});
If You use #Multipart than use #Part not #Field
public interface APIInterface {
#Multipart
#POST("addProject")
Call<AddProjectResponse> post(
#Part ("token") String token,
#Part ("name") String name,
#Part ("amount") String amount,
#Part ("description") String description,
#Part ("category") String category,
#Part ("deadline") String deadline,
#Part MultipartBody.Part img
);
}
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 am trying to call web service which receives responsive array. I am sending Hash map with values using retrofit in android but it is giving me 500 internal server error.Following is my code:
#POST("/save")
public void CreateAccount(
#Body Map<String, String> data,
Callback<Response> callback);
That's how you can do this with Retrofit 2
Interface:
#POST("/save")
Call<JsonElement> CreateAccount(#Body RequestBody requestBody);
Request code:
//create JsonObject with key-pair values
JsonObject root = new JsonObject();
root.addProperty("key1", "value1");
root.addProperty("key2", "value2");
//get is as string
String resultJson = root.toString();
//parse it to RequestBody type
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), resultJson);
//create adapter
Retrofit restAdapter = new Retrofit.Builder()
.baseUrl(Constants.ROOT_API_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
IConstructSecureAPI service = restAdapter.create(IConstructSecureAPI.class);
Call<JsonElement> result = service.CreateAccount(requestBody);
result.enqueue(new Callback<JsonElement>() {
#Override
public void onResponse(Call<JsonElement> call, retrofit2.Response<JsonElement> response) {
if(response.isSuccessful()){
JsonElement jsonElement = response.body();
JsonObject withResponse = jsonElement.getAsJsonObject();
}
else{
System.out.println(response.message());
}
}
#Override
public void onFailure(Call<JsonElement> call, Throwable t) {
}
});