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) {
}
});
Related
So I have a JSONObject's object and I need to send the object to backend using Retrofit. It is a POST api and the body is of jsonObject. The following code I have written send JSONObject.
This is interface
public interface ApiSet {
#POST(Api.DELETE_EWAYBILL)
Call<JsonElement> deleteEwaybill(#Body JSONObject jsonObject);
}
This code I written in adapter
Call<JsonElement> call = ApiController.getInstance()
.getApi()
.deleteEwaybill(deleteEwayObj);
Log.e("vin1", deleteEwayObj.toString());
call.enqueue(new Callback<JsonElement>() {
#Override
public void onResponse(Call<JsonElement> call, retrofit2.Response<JsonElement> response) {
if (response.isSuccessful()) {
Gson gson = new Gson();
JsonElement jsonElement = response.body();
if(jsonElement.isJsonObject()){
JsonObject jsonObject = jsonElement.getAsJsonObject();
PostResponse postResponse = gson.fromJson(jsonObject, PostResponse.class);
if(postResponse.isSuccess()){
((Activity) context).recreate();
}else{
Toast.makeText(context,postResponse.getMessage(),Toast.LENGTH_LONG).show();
Log.e("vin1", "delete invoice error = "+postResponse.getMessage());
}
}
}
customProgressDialog.dismiss();
}
#Override
public void onFailure(Call<JsonElement> call, Throwable t) {
Log.e("vin1", "retrofit failure = " + t.getMessage());
customProgressDialog.dismiss();
t.printStackTrace();
}
});
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
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"
}
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());
}
}
I am using retrofit to get data from http URL.
My Interface Class :
public interface SlotsAPI {
/*Retrofit get annotation with our URL
And our method that will return a Json Object
*/
#GET(url)
retrofit.Call<JSONObject> getSlots();
}
My request method.
public void getResponse(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
//Creating an object of our api interface
SlotsAPI api = retrofit.create(SlotsAPI.class);
retrofit.Call<JSONObject> callback = api.getSlots();
callback.enqueue(new Callback<JSONObject>() {
#Override
public void onResponse(Response<JSONObject> response) {
if (response != null) {
Log.d("OnResponse", response.body().toString());
}
}
#Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
});
}
In the response I am receiving an empty body.And the server responds with 200 OK.
D/OnResponse: {}
But when I open the URL in browser I am getting JSONObject on the screen.
you should try like this way ....
public interface SlotsAPI {
/*Retrofit get annotation with our URL
And our method that will return a Json Object
*/
#GET(url)
Call<JsonElement> getSlots();
}
in request method
retrofit.Call<JsonElement> callback = api.getSlots();
callback.enqueue(new Callback<JsonElement>() {
#Override
public void onResponse(Response<JsonElement> response) {
if (response != null) {
Log.d("OnResponse", response.body().toString());
}
}
Please check your JsonObject. If you want to get response in json you must be define a response type JsonObject not JSONObject other wise specify the pojo class in your interface.
I think you are not understanding the retrofit filosofy.
The correct interface should be:
public interface SlotsAPI {
/*Retrofit get annotation with our URL
And our method that will return a Json Object
*/
#GET(url)
JSONObject getSlots();
}
When you call the getSlots method, retrofit will automatically do the HTTP request and return the JSONObject.
You will need to do this out of the main thread.
Make sure that the url of #Get is relative path
#Base URL: always ends with /
#Url: DO NOT start with /
Example:
String URL = http://api.co/base/ ;
And
#GET("webservice/syncdown")
JSONObject getSlots();
You may receiving a list of Slots. the Gson converter will handle it if you sending array of json
#GET(url)
retrofit.Call<List<Slot>> getSlots();
You are using the retrofit 2 or 1? The version 2 still is in beta.
If you are using the version 1. Use this:
public interface SlotsAPI {
/*Retrofit get annotation with our URL
And our method that will return a Json Object
*/
#GET(url)
void getSlots(Callback<JsonElement> callback);
}
With this the call will be asynchronous.
Same problem here, and answer from curiousMind saved my day.
More on the same subject: if you need to get a value from a pair use:
String value = response.body().getAsJsonObject().get("pair_name").getAsString();
Call<Void> getSlots() worked for me.
private void APIRetrofit_method() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(RecyclerInterface.JSONURL)
// .client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
RecyclerInterface api = retrofit.create(RecyclerInterface.class);
Call<ResponseBody> call = api.getString(); /// GET METHOD without passing params
// Post METHOD CODE START
// HashMap<String, String> params = new HashMap<String, String>();
// params.put("name", "yuva");
// params.put("pass", "" + "123");
// Call<ResponseBody> call1 = api.getProspectList(params);
// Post METHOD CODE END
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
Log.d(TAG, "GetProspectlistresponse" + "" + response.isSuccessful());
utility.hideProgressDialog();
if (response.isSuccessful()) {
String remoteResponse = new String(response.body().string());
Log.d(TAG, "Holidaylistresponse" + "" + remoteResponse);
try {
JSONObject object = new JSONObject(remoteResponse);
JSONArray array = object.getJSONArray("Holidays_Details");
if (array.toString().equals("[]")) {
holiday_recyclerView.setVisibility(View.GONE);
} else {
holiday_recyclerView.setVisibility(View.VISIBLE);
for (int i = 0; i < array.length(); i++) {
JSONObject c = array.getJSONObject(i);
String holidayDate = c.getString(TAG_HOLIDAYDATE);
String holidayName = c.getString(TAG_HOLIDAYName);
String holidaytype = c.getString(TAG_HOLIDAYtype);
HashMap<String, String> customers = new HashMap<String, String>();
customers.put(TAG_HOLIDAYDATE, holidayDate);
customers.put(TAG_HOLIDAYName, holidayName);
customers.put(TAG_HOLIDAYtype, holidaytype);
arrayList.add(customers);
}
getHolidaylistAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
utility.hideProgressDialog();
}
} catch (IOException e) {
e.printStackTrace();
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.i("ErrorResponsestring", call.toString());
}
});
}
String JSONURL = "https://demonuts.com/Demonuts/JsonTest/Tennis/";
#GET("json_parsing.php")
Call<ResponseBody> getString();
// #POST("getProspectList")
// #FormUrlEncoded
// Call<ResponseBody> getProspectList(#FieldMap HashMap<String, String> body);
implementation 'com.squareup.retrofit2:retrofit:2.0.2'
implementation 'com.squareup.retrofit2:converter-gson:2.0.2'
implementation 'com.squareup.okhttp3:okhttp:4.0.0'