Hi i have a json to send to the server (POST METHORD){"country":"india","devicetype":"android"} it is in form data model
like the key for this json is data ie is the server accept it like
data={"country":"india","devicetype":"android"} am using retrofit i use Multipart like this
#Multipart
#POST("initiate")
#Headers({
"Content-Type: application/json",
"Cache-Control: no-cache"
})
Call<UserInfoServerResponse> getUserInfoRequest(#Part(value="data") UserInfo mUserInfo);
here UserInfo is the json but am getting fail message from server after that i used FormUrlEncoded methord
#FormUrlEncoded
#POST("initiate")
#Headers({
"Content-Type: application/json",
"Cache-Control: no-cache"
})
Call<UserInfoServerResponse> getUserInfoRequest(#Field(value="data",encoded = false) String mUserInfo);
its out put is also same failure result from server, but the data sending to the server is in the formate
data=%7B%22country%22%3A%22india%22%2C%22devicetype%22%3A%22%22%7D
My UserInfo.class
public class UserInfo {
public String country;
public String devicetype;
public UserInfo( String country,String devicetype) {
this.country=country;
this.devicetype=devicetype;
}
}
My adaptor class
RemoteRetrofitInterfaces mService;
Retrofit mRetrofit;
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS).addInterceptor(interceptor)
.build();
mRetrofit = new Retrofit.Builder()
.baseUrl(AppConstant.HOST).addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
mService = mRetrofit.create(RemoteRetrofitInterfaces.class);
Call<UserInfoServerResponse> api = mService.getUserInfoRequest(new Gson().toJson(mUserInfo));
api.enqueue(new Callback<UserInfoServerResponse>() {
#Override
public void onResponse(Call<UserInfoServerResponse> responseCall, Response<UserInfoServerResponse> response) {
if (response.body().status != null) {
if (response.body().status.equals("success")) {
Log.d(TAG, "success---");
}
} else {
Log.d(TAG, "Failed---");
}
}
#Override
public void onFailure(Call<UserInfoServerResponse> responseCall, Throwable t) {
t.printStackTrace();
}
});
so how can i send the json to server using retrofit successfully i gone through the retofit document and follow couple of steps but i dont get any result. can any one help me in this
Thank you
finally i found the solution hope this will help some other
i achieve the solution by using FieldMap
of retrofit.
#POST("initiate")
#FormUrlEncoded
Call<UserInfoServerResponse> getUserInfoRequest(#FieldMap Map<String,String> params);
and in the Rest Adaptor section i changed request data from string to Hashmap form like following
Log.d(TAG, "sendUserInfo called");
UserInfo mInfo = new UserInfo("countyname","android");
String request = new Gson().toJson(mUserInfo);
// Here the json data is add to a hash map with key data
Map<String,String> params = new HashMap<String, String>();
params.put("data", request);
Call<UserInfoServerResponse> api = mService.getUserInfoRequest(params);
api.enqueue(new Callback<UserInfoServerResponse>() {
#Override
public void onResponse(Call<UserInfoServerResponse> responseCall, Response<UserInfoServerResponse> response) {
if (response.body().status != null) {
if (response.body().status.equals("success")) {
Log.d(TAG, "success---" + response.body());
}
} else {
Log.d(TAG, "Failed---");
}
}
#Override
public void onFailure(Call<UserInfoServerResponse> responseCall, Throwable t) {
t.printStackTrace();
}
});
Basilcally what I used #FormUrlEncoded for form data and #FieldMap to put my request JSON as a key value. i got solution by following this method, hope this will help some one :)
The above solution works but is cumbersome to use , a better solution will be to use a converter for #Multipart formData
Please use the bellow code for proceeding with #Multipart FormData
This is because
"" is added to your posting strings
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
/**
* Created by kural on 10/27/17.
*/
public class StringConverterFactory extends Converter.Factory {
private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain");
public static StringConverterFactory create() {
return new StringConverterFactory();
}
#Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
if (String.class.equals(type)) {
return new Converter<ResponseBody, String>() {
#Override
public String convert(ResponseBody value) throws IOException {
return value.string();
}
};
}
return null;
}
#Override
public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
if (String.class.equals(type)) {
return new Converter<String, RequestBody>() {
#Override
public RequestBody convert(String value) throws IOException {
return RequestBody.create(MEDIA_TYPE, value);
}
};
}
return null;
}
}
and in your retrofit client add this line
.addConverterFactory(StringConverterFactory.create())
public class RetroFitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
if (retrofit==null) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
/*retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();*/
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(client)
.addConverterFactory(StringConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
This works fine for me and return a json to obtain new valid Microsoft Azure Token :
My end point :
#PostMapping(value = "/get-new-token", consumes = {"application/JSON"}, produces = {"application/JSON"})
#Timed
public ResponseEntity<String> getNewToken(#RequestBody String refreshToken) throws IOException {
JSONObject json = tokenService.getNewTokenByRefreshToken(refreshToken);
return new ResponseEntity<>(json.toString(), HttpStatus.OK);
}
My getGraphRepository :
public GraphRepository getGraphRepository() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor).build();
// Create and configure the Retrofit object
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(" https://login.microsoftonline.com")
.client(client)
.addConverterFactory(JacksonConverterFactory.create())
.build();
// Generate the graph repo
return retrofit.create(GraphRepository.class);
}
My Token Service :
public JSONObject getNewTokenByRefreshToken(String refreshToken) throws IOException {
GraphRepository graphRepository = getGraphRepository();
// My list of -> Key : Value
Map<String,String> params = new HashMap<String, String>();
params.put("grant_type", "refresh_token");
params.put("client_id", this.client_id);
params.put("client_secret", client_secret);
params.put("refresh_token", refreshToken);
RefreshToken data = graphRepository.getRefreshToken(tenantId, params).execute().body();
JSONObject json = new JSONObject(data);
return json;
}
My GraphRepository :
#POST("/{tenant_id}/oauth2/v2.0/token")
#FormUrlEncoded
Call<RefreshToken> getRefreshToken(
#Path("tenant_id") String tenant_id,
#FieldMap Map<String, String> params
);
I hope this can help someone.
Related
I have an android studio application that connects to a nodejs backend server with user authentication. I can log in and register from my app but it does not store a session. So I can not get session based functionality yet.
I need to add functionality to store a session. For this how do I do this with the retrofit interface.
I want to log in start a session so I can have user logged in access to other routes on the server.
Or is there another interface for android studio that will allow for cookies and sessions?
Retrofit interface
public interface RetrofitInterface {
#POST("/login")
Call<Login_result> executeLogin(#Body HashMap<String, String> map);
#POST("/signup")
Call<Void> executeSignup(#Body HashMap<String, String>map);
#POST("/add_data")
Call<Void> executeAdd_data(#Body HashMap<String, String>map);
#POST("/logout")
Call<Void> executeLogout(#Body HashMap<String, String>map);
#GET("/test")
Call<Void> executeTest();
}
**Main code**
```java
/*Updated this*/
Context context = this;
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(new OkhttpClient.builder()
.addInterceptor(new ReceivedCookiesInterceptor(context)
.addInterceptor(new AddCookiesInterceptor(context)
).build())
.addConverterFactory(GsonConverterFactory.create())
.build();
retrofitInterface = retrofit.create(RetrofitInterface.class);
Log in code
HashMap<String,String> map = new HashMap<>();
//map.put("email",emailEdit.getText().toString());//
map.put("username", usernameEdit.getText().toString());
map.put("password", passwordEdit.getText().toString());
Call<Login_result> call =
retrofitInterface.executeLogin(map);//Run the post
call.enqueue(new Callback<Login_result>()
{
#Override
public void onResponse(Call<Login_result> call, Response<Login_result> response) {
if(response.code() == 200)
{
/*Login_result result = response.body();
AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
builder1.setTitle(result.getUsernname());
builder1.setMessage(result.getEmail());
builder1.show();*/
Toast.makeText(MainActivity.this, "Logged in", Toast.LENGTH_SHORT).show();
}else if(response.code() == 404)
{
Toast.makeText(MainActivity.this, "Incorrect usernanme or password", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<Login_result> call, Throwable t) {
Toast.makeText(MainActivity.this, t.getMessage(),Toast.LENGTH_LONG).show();
}
});
You would need to create an two interceptors and store the cookie information in Shared Preferences
public class ReceivedCookiesInterceptor implements Interceptor {
private Context context;
public ReceivedCookiesInterceptor(Context context) {
this.context = context;
}
#Override
public Response intercept(Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
if (!originalResponse.headers("Set-Cookie").isEmpty()) {
HashSet<String> cookies = (HashSet<String>) PreferenceManager.getDefaultSharedPreferences(context).getStringSet("PREF_COOKIES", new HashSet<String>());
for (String header : originalResponse.headers("Set-Cookie")) {
cookies.add(header);
}
SharedPreferences.Editor memes = PreferenceManager.getDefaultSharedPreferences(context).edit();
memes.putStringSet("PREF_COOKIES", cookies).apply();
memes.commit();
}
return originalResponse;
}
}
And then reverse to add cookies to the outgoing request
public class AddCookiesInterceptor implements Interceptor {
public static final String PREF_COOKIES = "PREF_COOKIES";
private Context context;
public AddCookiesInterceptor(Context context) {
this.context = context;
}
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request.Builder builder = chain.request().newBuilder();
HashSet<String> preferences = (HashSet<String>) PreferenceManager.getDefaultSharedPreferences(context).getStringSet(PREF_COOKIES, new HashSet<String>());
Request original = chain.request();
if(original.url().toString().contains("distributor")){
for (String cookie : preferences) {
builder.addHeader("Cookie", cookie);
}
}
return chain.proceed(builder.build());
}
}
Which then you would need to change your Retrofit instance to the below
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(new OkhttpClient.builder()
.addInterceptor(new ReceivedCookiesInterceptor(context)
.addInterceptor(new AddCookiesInterceptor(context)
).build())
.addConverterFactory(GsonConverterFactory.create())
.build();
retrofitInterface = retrofit.create(RetrofitInterface.class);
I'm new to android development and trying to learn it. I recently ran into an issue, when I use get method I get a response as below:
As there is a status given as '0' from the backend I'm unable to catch the "response_data" array.
Could anyone please guide me how can I catch the response.
Thanks.
API CLIENT:
public class ApiClient {
private final static String BASE_URL = "http://api.xxxxxx.com/app/";
public static ApiClient apiClient;
private Retrofit retrofit = null;
public static ApiClient getInstance() {
if (apiClient == null) {
apiClient = new ApiClient();
}
return apiClient;
}
public Retrofit getClient() {
return getClient(null);
}
private Retrofit getClient(final Context context) {
HttpLoggingInterceptor interceptor = new
HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
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 okhttp3.Response intercept(Chain chain) throws
IOException {
Request request = chain.request();
return chain.proceed(request);
}
});
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
}
MAIN ACTIVITY:
public class MainActivity extends AppCompatActivity {
TextView tvResponse;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvResponse=findViewById(R.id.tvResponse);
ApiInterface apiInterface = ApiClient.getInstance().getClient().create(ApiInterface.class);
Call<ResponseData> responseDataCall=apiInterface.getData();
responseDataCall.enqueue(new Callback<ResponseData>() {
#Override
public void onResponse(Call<ResponseData> call, Response<ResponseData> response) {
if (response.isSuccessful() && response.body()!=null && response!=null){
List<ResponseDataItem> data=response.body().getResponseData();
}
}
#Override
public void onFailure(Call<ResponseData> call, Throwable t) {
t.printStackTrace();
}
});
}
}
RESPONSE DATA:
public class ResponseData {
#SerializedName("response_data")
private List<ResponseDataItem> responseData;
#SerializedName("status")
private int status;
public void setResponseData(List<ResponseDataItem> responseData){
this.responseData = responseData;
}
public List<ResponseDataItem> getResponseData(){
return responseData;
}
public void setStatus(int status){
this.status = status;
}
public int getStatus(){
return status;
}
}
In this case you need to let Gson know how you want to parse your json.
You can add many specific TypeAdapter's for each specific class case or you can create one TypeAdapterFactory that will be used to parse all your jsons. Remember to add it to your Retrofit builder.
This code example is a TypeAdapterFactory that will ignore status and parse only response_data to your object.
class ResponseDataTypeAdapterFactory implements TypeAdapterFactory {
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
TypeAdapter<JsonElement> elementTypeAdapter = gson.getAdapter(JsonElement.class);
return new TypeAdapter<T>() {
public void write(JsonWriter out, T value) throws IOException {
delegate.write(out, value);
}
public T read(JsonReader reader) throws IOException {
JsonElement jsonElement = elementTypeAdapter.read(reader);
if (jsonElement.isJsonObject()) {
JsonObject jsonObject = jsonElement.getAsJsonObject();
if (jsonObject.has("response_data")) {
jsonElement = jsonObject.get("response_data");
}
}
return delegate.fromJsonTree(jsonElement);
}
};
}
}
And on your Retrofit builder
Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(ResponseDataTypeAdapterFactory())
.create();
new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client.build())
.addConverterFactory(new GsonConverterFactory.create(gson))
.build();
And at the Retrofit interface, you only need to call the class that corresponds with response_datamapping.
public interface ApiInterface {
#GET("/product-data")
Call<List<ResponseDataItem>> fetchData();
}
With this implementation, you can remove your ResponseData class and care only about the important model.
Make an interface
public interface ApiInterface {
#GET
Call<JsonElement> getTimeDifference(#Url String url);
}
Crate an Retrofit client calss
public class RetrofitClient {
private static final String TAG = "RetrofitClient";
public static Retrofit geBaseUrl() {
Retrofit retrofit = null;
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
if (BuildConfig.DEBUG) {
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
}else{
interceptor.setLevel(HttpLoggingInterceptor.Level.NONE);
} OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl("...your base url...")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
String endpoint = "...your end point...";
ApiInterface ret = RetrofitClient.geBaseUrl(url).create(ApiInterface.class);
Call<JsonElement> call = ret.getTimeDifference(endpoint);
call.enqueue(new Callback<JsonElement>() {
#Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
try {
Log.d("String", "onResponse: response" + response.body().toString());
} catch (Exception e) {
}
}
#Override
public void onFailure(Call<JsonElement> call, Throwable t) {
Log.d("response", "onFailure: " + t + " " + call);
}
});
For Catching response you use interceptor like HttpLoggingInterceptor ,stetho,chuck
Creating the Retrofit instance
// Add the interceptor to OkHttpClient
OkHttpClient client=new OkHttpClient().newBuilder()
.addNetworkInterceptor(new StethoInterceptor()) \\ StethoInterceptor
.addInterceptor(new ChuckInterceptor(context)) \\ ChuckInterceptor
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.MINUTES)
.writeTimeout(5, TimeUnit.MINUTES)
.build();
public static final String BASE_URL = "http://api.myservice.com/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
for stetho interceptor
implementation 'com.facebook.stetho:stetho:1.5.0'
implementation 'com.facebook.stetho:stetho-okhttp3:1.5.0'
for chuck
debugImplementation 'com.readystatesoftware.chuck:library:1.1.0'
releaseImplementation 'com.readystatesoftware.chuck:library-no-op:1.1.0'
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 am hitting this API https://westus.dev.cognitive.microsoft.com/docs/services/563309b6778daf02acc0a508/operations/563309b7778daf06340c9652/console
below is my retrofit code. I am not able to send raw JSON in retrofit.
public void createProfileAPI()
{
ApiInterface apiService = ApiClient.getClientRequest().create(ApiInterface.class);
try
{
//pbVrd.setVisibility(View.VISIBLE);
JSONObject paramObject = new JSONObject();
paramObject.put("locale", "en-us");
LocaleModel localeModel = new LocaleModel();
localeModel.setLocale("en-us");
Call<BaseModel> call = apiService.SearchResponse(localeModel);
call.enqueue(new Callback<BaseModel>()
{
#Override
public void onResponse(Call<BaseModel> call, Response<BaseModel> response)
{
int responseCode = response.code();
Log.d("Deepakw" , responseCode+"");
BaseModel response1 = response.body();
Log.d("Deepak" , response.body().getIdentificationProfileId() + " //// " +response1.getIdentificationProfileId()+"");
}
#Override
public void onFailure(Call<BaseModel> call, Throwable t)
{
Log.d("Responce Failed ", "failed Response Mersen Fuse ");
String message = t.getMessage();
Log.d("failure", message);
}
});
}
catch (Exception e)
{
e.printStackTrace();
}
}
public class ApiClient {
public static final String BASE_URL = "https://westus.api.cognitive.microsoft.com/spid/v1.0/";
private static Retrofit retrofit = null;
public static Retrofit getClientRequest() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
public interface ApiInterface {
#Headers({
"Content-Type: application/json",
"Ocp-Apim-Subscription-Key: 0219cf3e3d444f0584f80b3a84613d12"
})
#POST("verificationProfiles")
Call<BaseModel> SearchResponse(#Body LocaleModel body);
};
I am not able to get response
API client
Please help
//In ApiInterface do like this
#Headers("charset:UTF-8")
#POST("verificationProfiles")
Call<BaseModel> SearchResponse(
#Header("Content-Type") String contentType,
#Body LocaleModel body);
have you tried #SerializedName("") and #Expose in your pojo class
#SerializedName("status")
#Expose
private Boolean status;
Instead of JSONObject, you can use Map
For example:
Headers("Content-Type: application/json")
#POST("/apipath")
request(#Body Map<String, String> body);
I am working on a project which will retrieve and send data to server through django api. I am facing problem to POST data through the api. My codes are given below. Executing this code give 401 Error in response in android studio but the api works fine in postman or web browser. TIA for the help.
Class to set retrofit instance:
public class ApiClient {
public static final String BASE_URL = "https://myapilink.com/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
final OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.header("Authorization", "auth-value"); // <-- this is the important line
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
final OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.header("Authorization", "Basic YWRtaW46MTIzNA=="); // <-- this is the important line
Request request = requestBuilder.build();
return chain.proceed(request);
}
})
.build();
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
.client(okHttpClient)
.build();
}
return retrofit;
}
Retrofit interface:
public interface ApiInterface {
#Headers("Content-Type: application/json")
#POST("/api/auth/login/")
Call<LoginModel> getLoginResponseWithRetrofit(#Body LoginBody loginBody);
}
LoginBody model:
public class LoginBody {
String email;
String password;
public LoginBody(String email, String password){
this.email=email;
this.password=password;
}
}
Main api calling method:
public void postDataWithRetrofit(String email, String password){
//modelFromIDProvider.add(InternalDataProvider.getInstance().getAgentDataModelList());
int selectedPosition,id;
LoginBody loginBody = new LoginBody(email, password);
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<LoginModel> call;
Map<String, String> formData = new HashMap<>();
formData.put("email", email);
formData.put("password", password);
Log.d(TAG,"formdata "+formData.toString());
//call = apiService.getLoginResponseWithRetrofit(email, password);
call = apiService.getLoginResponseWithRetrofit(loginBody);
call.enqueue(new Callback<LoginModel>() {
#Override
public void onResponse(Call<LoginModel> call, Response<LoginModel> response) {
Log.d(TAG,"isSuccessful "+response.isSuccessful()+" code "+response.code());
Log.d(TAG,"Data from response : "+response.body());
if(!response.isSuccessful()) {
dialog.dismiss();
return;
}
LoginModel responseModel = response.body();
InternalDataProvider.getInstance().setLoginDataModel(responseModel);
Log.d(TAG,"Data from response : "+response.body());
}
#Override
public void onFailure(Call<LoginModel> call, Throwable t) {
if(call.isCanceled()){
Log.d(TAG," call cancelled "+t.toString());
return;
}
Log.d(TAG," inside onFailure "+t.toString());
}
});
}