Unable to perform POST request with retrofit android - android

While I am trying to perform the post request with retrofit, it is throwing timeout exception. While using postman the API Url is working perfectly fine. Is there any error in the code. This is my code:
ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("accessToken", token);
Log.e("Token Object", jsonObject.toString());
} catch (JSONException e) {
e.printStackTrace();
}
Call<ResponseBody> callUser = apiInterface.facebookLogin(jsonObject);
dialog.show();
callUser.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.code() == 200)
Log.e("Token Object", response.toString());
dialog.dismiss();
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(getContext(), "Sorry! Somme Error Occured" + t.toString(), Toast.LENGTH_LONG).show();
dialog.dismiss();
}
});
This is the interface:
//facebook login
#POST("/api/users/facebooklogin")
Call<ResponseBody> facebookLogin(#Body JSONObject jsonObject);
This is the Retrofit Client
public class ApiClient {
public static final String BASE_URL = "http://192.168.100.15:8000/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(100, TimeUnit.SECONDS)
.readTimeout(100,TimeUnit.SECONDS).build();
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
This is the successful postman request

Pass the request parameters as RequestBody as follows:
#POST("/api/users/facebooklogin")
Call<ResponseBody> facebookLogin(#Body RequestBody request);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("accessToken", token);
Log.e("Token Object", jsonObject.toString());
} catch (JSONException e) {
e.printStackTrace();
}
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
Call<ResponseBody> callUser = apiInterface.facebookLogin(requestBody);

Related

Retrofit2 returns 999 when I called api

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

Getting error code 400 bad request in retrofit but works on postman

I'm working on an Registraion API
which takes the json input as follow / request perameters
{"httpMethod":"POST",
"firstname":"Ali",
"lastname":"Patel",
"email":"alipatel05#gmail.com",
"password":"12345678",
"country":"Canada",
"state":"Quebec",
"city":"Montreal",
"type":"Parent"}
but when i call the api from android app it gives me bad response with error code 400 but works pretty fine on postman.
my API Client
public class APIClient {
private static Retrofit retrofit = null;
public static final String BASE_URL = "https://5r8ndtx9zc.execute-api.us-east-2.amazonaws.com/";
public static Retrofit getClient() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
/*Gson gson = new GsonBuilder()
.setLenient()
.create();*/
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
return retrofit;
}
}
my API interface
public interface APIInterface {
#Headers({
"Content-Type: application/json;charset=utf-8",
"Accept: application/json;charset=utf-8",
"Cache-Control: no-cache"
})
#POST("vaccinesApi")
Call<ResponseBody> registerUser(#Body JSONObject locationPost);
}
and here's my api call
private void registerUser() {
HashMap<String, String> newhashMap = new HashMap<>();
JSONObject hashMap = new JSONObject();
try {
hashMap.put("httpMethod","POST");
hashMap.put("firstname",mEditFirstName.getText().toString().trim());
hashMap.put("lastname",mEditLastName.getText().toString().trim());
hashMap.put("email",mEditEmail.getText().toString().trim());
hashMap.put("password",mEditPassword.getText().toString().trim());
hashMap.put("country","Canada");
hashMap.put("state","Quebec");
hashMap.put("city",mSelectedCity);
hashMap.put("type",mUserType);
} catch (JSONException e) {
e.printStackTrace();
}
Call<ResponseBody> call = apiInterface.registerUser(hashMap);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
progressDialog.hide();
try {
JSONObject jsonObject = new JSONObject(response.body().toString());
Log.e("SignupFragment", jsonObject.toString());
if (response.code() == 200) {
Toast.makeText(RegistrationActivity.this, "Success",Toast.LENGTH_SHORT).show();
/*Intent intent = new Intent(RegistrationActivity.this, LoginActivity.class);
startActivity(intent);
finishAffinity();*/
} else {
Toast.makeText(RegistrationActivity.this, "Failed",Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
progressDialog.hide();
call.cancel();
Toast.makeText(RegistrationActivity.this, "Failed",Toast.LENGTH_SHORT).show();
}
});
}
Should i need to changes my interface or there may be some error in my api call?
Thanks in andvance
The issue is with your locationPost type, it should be JsonObject and not JSONObject, so try one of the following approaches
Approach 1
Api Interface
Call<ResponseBody> registerUser(#Body JsonObject locationPost);
Api call
JsonObject obj = new JsonObject();
obj.addProperty("httpMethod","POST");
obj.addProperty("firstname",firstNameValue);
// add the rest of the field
Call<ResponseBody> call = apiInterface.registerUser(obj);
//rest of the logic remains same
Approach 2
create a POJO class representing the object and pass the instance of the object
public class RequestObject{
final String httpMethod, firstname;
// declare member variables for all the keys
RequestObject(String method,String firstname){
this.httpMethod = method;
this.firstname = firstname;
}
}
API Interface
Call<ResponseBody> registerUser(#Body RequestObject locationPost);
Api call
RequestObject requestobject = new RequestObject("POST","firstName");
// add the rest of the field
Call<ResponseBody> call = apiInterface.registerUser(requestObject);
//rest of the logic remains same
I think you have to re-check these parameters carefully.
{
"httpMethod": "POST",
"firstname": "Ali",
"lastname": "Patel",
"email": "alipatel05#gmail.com",
"password": "12345678",
"country": "Canada",
"state": "Quebec",
"city": "Montreal",
"type": "Parent"
}

Retrofit json data passing

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();
}

Retrofit response does not contain response data

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);

How to convert the json object response from retrofit success response?

I have worked with retrofit file upload. Here by using system.out.println I can track the response body. But can't convert the response to JSON object.
I hereby write my code. Kindly please let me know how do I parse and get the string value using retrofit success message and failure message.
ApiConfig:
public interface ApiConfig {
#Multipart
#POST("general/Candidate/fileUpload")
Call<ResponseBody> upload(
#Header("Authorization") String authorization,
#PartMap Map<String, RequestBody> map,
#Part("id") RequestBody id,
#Part("fileCount") RequestBody fileCount,
#Part("fileType") RequestBody fileType,
#Part("platform") RequestBody platform,
#Part("externalID") RequestBody externalID);
}
ServiceGenerator:
public class ServiceGenerator {
public static final String API_BASE_URL = "http://104.239.173.64/peoplecaddie-api/";
private static Retrofit retrofit = null;
private static OkHttpClient httpClient = new OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.build();
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create(new Gson()));
public static <S> S createService(Class<S> serviceClass) {
Retrofit retrofit = builder.client(httpClient).build();
return retrofit.create(serviceClass);
}
}
uploadFile1:
private void uploadFile1(Uri fileUri) {
progressDialog.show();
ApiConfig service =
ServiceGenerator.createService(ApiConfig.class);
File file = FileUtils.getFile(this, fileUri);
RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
Map<String, RequestBody> map = new HashMap<>();
map.put("fileContent0\"; filename=\"" + file.getName() + "\"", requestFile);
MultipartBody.Part body =
MultipartBody.Part.createFormData("fileContent0", file.getName(), requestFile);
String idStr = "1743";
String fileCountStr = "1";
String fileTypeStr = "SAMPLE";
String platformStr = "Android";
String externalIDStr = "portpolio";
RequestBody idReq =
RequestBody.create(
MediaType.parse("multipart/form-data"), idStr);
RequestBody fileCountReq =
RequestBody.create(
MediaType.parse("multipart/form-data"), fileCountStr);
RequestBody fileTypeReq =
RequestBody.create(
MediaType.parse("multipart/form-data"), fileTypeStr);
RequestBody platformReq =
RequestBody.create(
MediaType.parse("multipart/form-data"), platformStr);
RequestBody externalIDReq =
RequestBody.create(
MediaType.parse("multipart/form-data"), externalIDStr);
// finally, execute the request
Call<ResponseBody> call = service.upload("817b6ce98fd759e7f148b948246df6c1", map, idReq, fileCountReq, fileTypeReq, platformReq, externalIDReq);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call,
Response<ResponseBody> response) {
try {
System.out.println("Rrespppppp--->"+response.body().string());
Log.e("response", "response------------------>" + response.body().string());
JSONObject profileFileUploadResponse = new JSONObject(String.valueOf(response.body()));
Log.e("retro", "retroFileResp------------------>" + profileFileUploadResponse);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("Upload error:", t.getMessage());
}
});
}
Here upload file method I can track the response using. This works fine.
System.out.println("Rrespppppp--->"+response.body().string());
But while try to convert the JSON Object it will not work the error code is below. And please let me know how do i parse and get the success and failure response value using this code.
Log.e("response", "response------------------>" + response.body().string());
JSONObject profileFileUploadResponse = new JSONObject(String.valueOf(response.body()));
Log.e("retro", "retroFileResp------------------>" + profileFileUploadResponse);
Thanks in Advance.
**You have to use Gson to get JsonObject response like below.**
public interface getProfileInfo {
#GET("users/{userid}")
Call<JsonObject> getProfileData(#Path("userid") String userId);
}
private void getUserProfileInfo(String userId)
{
getProfileInfo postService=RetrofitApi.makeNetworkRequest().create(getProfileInfo.class);
Call<JsonObject> call = postService.getProfileData(userId);
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
System.out.println("user Info :" + response.body().getAsJsonObject());
setUserData(response.body().getAsJsonObject());
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
// Log error here since request failed
System.out.println("Error :" + t.getMessage());
}
});
}
Modified your code. Please try. You will get json object in result
Call<ResponseBody> call = service.upload("817b6ce98fd759e7f148b948246df6c1", map, idReq, fileCountReq, fileTypeReq, platformReq, externalIDReq);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call,
Response<ResponseBody> response) {
try {
System.out.println("Rrespppppp--->"+response.body().string());
Log.e("response", "response------------------>" + response.body().string());
//JSONObject profileFileUploadResponse = new JSONObject(String.valueOf(response.body()));
ResponseBody result = response.body();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("Upload error:", t.getMessage());
}
});
Retrofit Response is already in json format you can get item by
{ "result": [{ "fileId": 852, "status": 1, "pcData": { "id": 635, "filename": "IMG_20161122_175344.jpg", "filepath": "uploads\/peoplecaddie\/files\/1743_1480742360_IMG_20161122_‌​175344.jpg" } }] }
String fileid=response.body().getresult(0).getFileId();
String status=response.body().getresult(0).getStatus();
You can only call response.body().string() once. From the ResponseBody docs --
The response body can be consumed only once.
You try to consume the body on both of the following two lines
Log.e("response", "response------------------>" + response.body().string());
JSONObject profileFileUploadResponse = new JSONObject(String.valueOf(response.body()));
You can read it once into a variable and reuse that --
final String body = response.body().string();
Log.e("response", "response------------------>" + body);
JSONObject profileFileUploadResponse = new JSONObject(body);
That should fix your problem, but if you don't want to go further and don't want to deal with creating the JSONObject yourself, one of the benefits of retrofit it does deserialization as well. You are already configuring a gson converter to your retrofit, so you should be able to update your call to --
#Multipart
#POST("general/Candidate/fileUpload")
Call<ReturnObject> upload(...)
where ReturnObject is the POJO you want to deserialize to. You will have to update your response handler as well, to expect a ReturnObject type.
Try this, It will work
Change Call Type as JsonElement
#GET("LoginAPI")
Call<JsonElement> getLogin(#Query("Username") String userName,
#Query("Password") String password);
Get Json object from the response
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
try {
JSONObject object = new JSONObject(response.body().toString());
textView.setText(object.toString());
} catch (JSONException e) {
e.printStackTrace();
textView.setText(e.getMessage());
}
}

Categories

Resources