how to send data to therequest body to the server using retrofit - android

String Params_body = "{"mobileNumber":"9968599840"}";
String Params_head = "{"clientId":"C11","version":"v1","txnToken":"" + txnToken + ""}";

You have to define your service using the #Header and #Query annotations to indicate the params.
This is just an example of how your service should look like:
public interface RetrofitService {
#GET("/v1/your/endpoint")
Call<YourResponse> networkCall(
#Header("clientId") String clientId,
#Header("version") String version,
#Header("txnToken") String txnToken,
#Query("mobileNumber") String mobileNumber);
}
Then you just need to call the endpoint method and pass as parameter the values.

You can use #Body annotation and pass all the parameter as below class.
class ClienInfo
{
String clientId,
String version,
String txnToken,
String mobileNumber);
}
Use like this:-
#GET("/v1/your/endpoint")
Call<YourResponse> networkCall(#Body ClienInfo clientInfo);

Related

How to pass param stored in shared preference to retrofit as a parameter for another API

i would like to get a user email that's stored in shared preference and use that as a parameter to retrieve specific information from an array in the api..
Process :
After registeration, i store the user info(Email, id and full name) in shared preferences and the user list back end. And in the second Call. i want to use the email alone from shared preferences to retrieve the user settings.
in this case: i would use the email as a search parameter to get the number from this list
This is the list
{
"userID": "1",
"userName": "MyName",
"email": "mail#gmail.com",
"phoneNumber": "+1234567"
}
API.java
public interface API {
String BASE_URL = "http://base-url.com/";
#FormUrlEncoded
#POST("api/user/settings")
Call <UserSetModel> getUserSettings(#Field ("phoneNumber") String phoneNumber);
UserSetModel.java
#SerializedName("userID")
#Expose
private String userID;
....
....
#SerializedName("phoneNumber")
#Expose
private String phoneNumber;
// constuctors
// getter and setters
MainActivity.java
....
String phoneNumber = "";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(SampleApi.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
API api = retrofit.create(API.class);
Call<UserSetModel> call = api.getUserSettings(phoneNumber);
call.enqueue(new Callback<UserSetModel>() {
#Override
public void onResponse(Call<UserSetModel> call, Response<UserSetModel> response) {
response.body();
try {
String numb = response.body().getPhoneNumber();
}catch (Exception e){
....
#Override
public void onFailure(
.....
}
i don't know how to initiate the email from the user preferences to the post request
EDIT:
UserPreferences.java
public void setUserDetails(String Email, String Id, String FullName){
editor.putString(EMAIL_PREF, email)
.....
public String getEmail(String email){}
public String getid(String id){}
....
This is set in the signin Class below and is sent to the server
SignIn.Java
.....
String email = Edittext.gettext.toString;
String full name = Edittext2.gettext.toString;
....
userPreferences.setUserDetails(email,fullname,id);
Retrofit retrofit .....
EDIT: One user is stored in shared preference but all users are stored in the db. so i'm trying to use only the email from (SP) to retrieve the information from the api
EDIT:
as you want to use only email you have to save it separately to get it back when you need. code to do that will be like below:
public final String KEY_EMAIL="user_email";
public String getEmail(){
return sharedpreferences.getString(KEY_EMAIL,null);
}
public void setEmail(String email){
sharedprefEditor.putString(KEY_EMAIL,email);
sharedprefEditor.commit();
}
so when you need to pass it as #Field in retrofit interface call just get it back from sharedpreferences.
This is one way of doing this but I will advice you to make a Model class for your user like User.java with Serialized Fields and save it as a whole in sharedpreferences with Gson.
Link to Gson: Gson by Google
PREVIOUS ANSWER:
The question is not clear. What you are saving into the sharedpreference ? A particular user or a list of users?

Change user-type in API Header or change header using variable

I declare a final variable in global
public static final String USERTYPE="customer"
Then I use this variable as
#POST
#Headers({
"Content-Type: application/json;charset=utf-8",
"Accept: application/json;charset=utf-8",
"Cache-Control: max-age=640000",
"user-type: " + APIService.STRING
})
Call<ReturnPojo> addpost(#Url String s, #Body Add body);
Later in my program, I need to change the
USERTYPE="guest"
I try
1.USERTYPE.replace("customer","guest");
2.String user="customer"
USERTYPE=user;
How can I achieve this? or How to change a final variable in java?
You can't. You've declared USERTYPE as final so the only choice you have is to use a different String.
Change Header on Run-time(Retrofit API)
We cannot change the final variable, So we cannot change the user type programmatically. By duplicating the code is not good practice. But we can be done through this,
#POST
Call<ReturnPojo> addpost(#Url String s,
#Body Add body,
#Header("user-type") String user_type,
#Header("Content-Type") String content_type,
#Header("Accept") String accept,
#Header("Cache-Control") String cache_controller);
And finally, while we call API just pass the data as the parameter.

Android Retrofit 2 make POST request multiple params (without FormUrlEncoded)

I would like to make a POST request call with multiple params instead of one #Body param. I'm not using #FormUrlEncoded annotation on this one and I don't want to. I'm using Retrofit 2.0.
Currently, the call is made this way :
#POST("user/register")
Call<APIResponse> register(#Body RequestRegisterParams params);
with RequestRegisterParams being :
public class RequestRegisterParams {
public String username;
public String email;
public String password;
}
I would like to be able to do this (with proper annotations of course) :
#POST("user/register")
Call<APIResponse> register(String username, String email, String password);
My goal is to get rid of the data model class. Is there a way to do this or a POST request without #FormUrlEncoded must have only one #Body param ? I know it can only be one #Body param but maybe with other annotations ?
Thanks in advance !
#FormUrlEncoded
#POST("user/register")
Call<APIResponse> updateUser(#Field("username") String username, #Field("email") String email, #Field("password") String password);
#Field is Named pair for a form-encoded request.

Sending various parameters (JSON) using Retrofit 2

This is the interface method:
#FormUrlEncoded
#POST (“url/myurl")
Call<JsonArray> sendParameters (#Header("x-imei") String imei, #Header("x-id-cliente") String idCliente, #Field(“param1") JsonObject param1, #Field(“param2") JsonArray param2, #Field(“param3") JsonArray param3, #Field(“param4") JsonArray param4,#Field(“param5") JsonArray param5);
And the method to use it:
Call<JsonArray> peticion= RetrofitClient.getRetrofitClient(getActivity()).sendParameters(settings.getString("imei", ""), settings.getString("idCliente", "”),param1,param2,param3,param4,param5);
This way, the call is not working.
I tried changing all the interface parameters to String, and doing param1.toString(), param2.toString() and so on in the call, and is not working neither.
Is there a simple way to send JsonObjects and JsonArrays in a POST, using Retrofit 2?
Thank you.
First you can create a custom class which you want to pass as a POST body
class CustomClass {
String param1;
String parma2;
String param3;
//all of your params with getters and setters
}
Then you change the Retrofit method according to your new CustomClass instance with the #Body annotation:
#POST (“url/myurl")
Call<JsonArray> sendParameters (#Header("x-imei") String imei, #Header("x-id-cliente") String idCliente, #Body CustomClass customClassInstance);
And eventually you make the call to post data:
CustomClass customClassInstance = new CustomClass();
customClassInstance.setParam1(...);
//...and so on
Call<JsonArray> peticion= RetrofitClient.getRetrofitClient(getActivity()).sendParameters(settings.getString("imei", ""), settings.getString("idCliente", ""), customClassInstance);
EDIT: removed the #FormUrlEncoded annotation

Retrofit ws error using #Query

I have try this interface :
public interface InterfaceWs
{
#GET("/?extract-mode=bestdeals&api-key={apikey}") public Observable<List<ModelBestDeals>> getBestDeals(#Query("apikey") String apikey);
}
Before using #Query I was using #Path. I change it
and I receive this error :
URL query string "extract-mode=bestdeals&api-key={apikey}" must not have replace block. For dynamic query parameters use #Query.
What is wrong ?
#GET("/?extract-mode=bestdeals&api-key={apikey}") public Observable<List<ModelBestDeals>> getBestDeals(#Query("apikey") String apikey);
should be
#GET("/?extract-mode=bestdeals") public Observable<List<ModelBestDeals>> getBestDeals(#Query("api-key") String apikey);
retrofit will take care of completing your url with api-key=value, where value is the value of apikey. You could also use a QueryMap to provide the other pair extract-mode=bestdeals. E.g.
Map<String, String> map = new HashMap<>();
map.put("extract-mode", "bestdeals");
map.put("api-key", apikey);
and your method
#GET("/") public Observable<List<ModelBestDeals>>
getBestDeals(#QueryMap Map<String, String> values);
which is, in my opinion, way more readable

Categories

Resources