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();
}
});
Related
I'm trying to read this JSON using Retrofit but I got this error Could not locate ResponseBody converter for class org.json.JSONObject.
The JSON in ALE2 file
{
"a1":[...],
"a2":[...],
"a3":[...]
}
Code
Retrofit retrofit = new Retrofit.Builder().baseUrl(Constants.BASE_URL).build();
retrofit.create(RetrofitInterface.class).getData().enqueue(new Callback < JSONObject > () {
#Override
public void onResponse(Call < JSONObject > call, Response < JSONObject > response) {
}
#Override
public void onFailure(Call < JSONObject > call, Throwable t) {
}
});
RetrofitInterface
public interface RetrofitInterface {
#GET("ALE2")
Call<JSONObject> getData();
}
I don't want to store them in any model I just want to get the JSON as a string
Your interface should look like this :
public interface RetrofitInterface {
#GET("ALE2")
Call<ResponseBody> getData();
}
To get raw json object return type should be Call<ResponseBody>
Once that is done in response you can handle it like below :
retrofit.create(RetrofitInterface.class).getData().enqueue(new Callback<ResponseBody> () {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
String responseBody = response.body().string();
JSONObject json = new JSONObject(responseBody);
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
This is how you can set string in JSON object.
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
every time i run this function onfaliure calls
json array
{"ORDER":[{"ORDER_DATE":"2020-09-08 01:28:11 PM","CUSTOMER_ID":"umersaleem_03334033313","PRODUCT_ID":"","QUANTITY":1,"DEAL_ID":"1","ORDER_TOTAL":"600.0"}
interface
#POST("/restaro/index.php/Home/insert_order_info")
Call<CheckloginModel> insertOrder(#Body JSONObject j);
function
retrofitApiInterface.insertOrder(orders)
.enqueue(new Callback<CheckloginModel>() {
#Override
public void onResponse(Call<CheckloginModel> call, Response<CheckloginModel> response) {
if (response.isSuccessful()) {
}
#Override
public void onFailure(Call<CheckloginModel> call, Throwable t) {
Toast.makeText(getApplicationContext(), "Poor internet connection or device is Off ", Toast.LENGTH_SHORT).show();
}
});
}
api response
this the response when the data is inserted through postman
{
"status": 1,
"message": "new order added "
}
when i send it on postman the data is inserting need help thanks in advance
#Headers("Content-Type: application/json")
#POST("/restaro/index.php/Home/insert_order_info")
Call< CheckloginModel> insertOrder(#Body RequestBody body);
request body send with your json and send this request body to api.
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("value", "value");
} catch (JSONException e) {
e.printStackTrace();
}
RequestBody requestBody=RequestBody.create(MediaType.parse("application/json; charset=utf-8"),jsonObject.toString());
I will only this line and pass requestbody Retrofit call and works for me
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject1.toString());
Call<CheckOutResponse> call = RetrofitClient.getInstance().getApi().postOrder(requestBody);
call.enqueue(new Callback<CheckOutResponse>() {
#Override
public void onResponse(Call<CheckOutResponse> call, Response<CheckOutResponse> response) {
CheckOutResponse checkOutResponse = response.body();
#Override
public void onFailure(Call<CheckOutResponse> call, Throwable t) {
}
});
Webservice class
#POST("yourAPiCall")
Call<CheckOutResponse> postOrder(#Body RequestBody requestBody);
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) {
}
});
Currently, I am using Retrofit to get data from api. But the format of data is a bit different from other format such as :
["tayl",["taylor swift","taylor swift kanye west","taylor swift famous","taylor swift mp3","taylor lautner","taylor swift wiki","taylor swift 1989","taylor hill","taylor swift 2016","taylor kinney"]]
So, I want to ask for the best solution to parse values to get a list as below if I want to use retrofit:
"taylor swift","taylor swift kanye west","taylor swift famous","taylor swift mp3","taylor lautner","taylor swift wiki","taylor swift 1989","taylor hill","taylor swift 2016","taylor kinney"
The content of the file above is the data which GoogleAutoComplete Api returned for me with the link below :
http://suggestqueries.google.com/complete/search?client=firefox&q=tayl
I implemented the code as below but it is not good:
#Headers({
"Accept: application/json",
"Content-Type: application/json; charset=UTF-8"
})
#GET("complete/search?")
Call<ResponseBody> getAutoComplete(#Query(#Query("q")String query);
The below is response code which I am using:
autoCompleteCall = googleApi.getAutoComplete(client, keyword);
autoCompleteCall.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response != null &&
response.body() != null) {
System.out.println(" String response======= " + response.body().toString());
return;
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
But the responsebody returned for me is null.
Please help me in this case.
Thanks.
Define the API endpoint in an interface as follows:
#GET("complete/search")
Call<ResponseBody> getAutoComplete(
#Query("client") String client,
#Query("q") String query);
Make the network request as follows:
Call<ResponseBody> call = service.getAutoComplete("firefox", "tayl");
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
ResponseBody body = response.body();
try {
// autocompleteOptions => ["tayl",["taylor swift","taylor lautner",...
String autocompleteOptions = body.string();
JSONArray jsonArray = new JSONArray(autocompleteOptions).getJSONArray(1);
// list => "taylor swift","taylor lautner",...
ArrayList<String> list = GetAutocompleteOptions(jsonArray);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
private ArrayList<String> GetAutocompleteOptions(JSONArray jsonArray) throws JSONException {
ArrayList<String> list = new ArrayList<>();
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
list.add(jsonArray.get(i).toString());
}
}
return list;
}