I am trying to integrate greendao with the retrofit. This link will give an idea ( https://i.stack.imgur.com/7qmbu.jpg) of how the data is sent to the server. It is a post request and I am really confused about how to call this request via retrofit.
It will be really helpful if someone can help me with it.
In API response I am getting an request object, response object, message and status code.
response object I have fields about the user and in request object I have field about the information that is being send.
another picture here
https://i.stack.imgur.com/a5DBz.jpg
You can create response like this using this method
private String create(String email, String password) {
try {
JSONObject cell1 = new JSONObject();
JSONObject jsonObject = new JSONObject();
cell1.put("email", email);
cell1.put("password", password);
jsonObject.put("data", cell1);
return jsonObject.toString();
} catch (Exception e) {
return e.getMessage();
}
}
Call you POST as this
#FormUrlEncoded
#POST("your_path_here")
Call<String> uploadData(#Body String obj);
in your Activity
String json = create("your_email", "your_password");
apiInterface.uploadData(json).enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
}
#Override
public void onFailure(Call<String> call, Throwable t) {
}
});
Related
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);
Im getting the "Value of type java.lang.String cannot be converted to JSONObject" error when trying to pass the response string to the JSON object. I've tried something similar in the past, and it worked, so I have no idea why it's happening.
Here's the code
public void searchMovie(){
OkHttpClient client = new OkHttpClient();
url = Constants.moviebaseurl + mEdit.getText();
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NotNull Call call, #NotNull IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException {
final String myResponse = response.body().toString();
SearchActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONObject json = new JSONObject(myResponse);
JSONArray results = json.getJSONArray("results");
mText.setText(results.getJSONObject(0).getString("title"));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
Am I doing something wrong, or am I just missing something? Thank you for your help!
It worked changing
final String myResponse = response.body().toString();
for
final String myResponse = response.body().string();
From referencing this question I was able to find this answer
Using google-gson you can do it like this:
JsonObject obj = new JsonParser().parse(myResponse).getAsJsonObject();
This question itself might even lead to some insight of the issue if my code doesn't work for you.
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'
I have to send the JSON as a Post request through Retrofit. To this I have created a Json Object :
private JSONObject yourJSON(){
JSONObject jsonRoot = new JSONObject();
JSONObject jsonObject1 = new JSONObject();
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject2 = new JSONObject();
try{
jsonArray.put(jsonObject2);
jsonObject2.put("duration", "12");
jsonObject1.put("region", "NYC");
jsonObject1.put("or", jsonArray);
jsonRoot.put("q", jsonObject1);
jsonRoot.put("sort", "recent");
}catch (JSONException e){
e.printStackTrace();
}
return jsonRoot;
}
Then I am using this JSON to send the data by following code
RestApiAdapter restAdapter = new RestApiAdapter();
RoomListingAPI apiservice = restAdapter.providesRestAdapter().create(RoomListingAPI.class);
JSONObject response = apiservice.getRoomListing("qwerty","application/json", yourJSON());
API method
public interface RoomListingAPI {
#POST("/api/listings/search")
JSONObject getRoomListing(#Header("x-parse-session-token") String token, #Header("Content-Type") String type, #Body JSONObject json);
}
My goal is to send the JSON and received the JSON but it's not working. What I am doing wrong here. I am also sending the correct JSON. What I am doing wrong here?
You should call your network operation on a background task instead. Otherwise, NetworkOnMainThreadException will be thrown.
Now retrofit has two modes. Synchronous or Asynchronous.
You're using a synchronous mode, presumably called in your main thread.
What you can do now is to change to asynchronous mode (using retrofit callback).
That is, change from:
public interface RoomListingAPI {
#POST("/api/listings/search")
JSONObject getRoomListing(#Header("x-parse-session-token") String token, #Header("Content-Type") String type, #Body JSONObject json);
}
To:
public interface RoomListingAPI {
#POST("/api/listings/search")
void getRoomListing(#Header("x-parse-session-token") String token, #Header("Content-Type") String type, #Body JSONObject json, Callback<JsonObject> responseCallback);
}
To get the JsonObject return response:
apiservice.getRoomListing("qwerty","application/json", yourJSON(),
new Callback<JsonObject>() {
#Override
public void success(JsonObject jsonObject, Response response) {
// jsonObject is what you're looking for
}
#Override
public void failure(RetrofitError error) {
// do something with the error
}
});
Also, it's better to use gson library. Thus use JsonObject instead of JSONObject. Different letter-case, different library, better performance.
I'm using the Android Asynchronous Http Client. My code looks like this and is working fine.
DataUtil.post("RegisterUser", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String answer) {
// initialize variables
JSONObject json = new JSONObject();
String message = null;
try {
// turn string into JSONObject
json = new JSONObject(answer);
message = json.getString("message");
} catch (JSONException e) {
Log.e("ERROR", e.getMessage());
}
// registration was successful
if (message.equals("success")) {
// forward to login page
} else {
// error
}
}
});
I implemented a static HTTP Client. My server returns this JSON data {"message":"success"}. I do not want to treat it as a String and cast it back to JSON. But when I change it to public void onSuccess(JSONObject answer) eclipse tells me
The method onSuccess(JSONObject) of type new
AsyncHttpResponseHandler(){} must override or implement a supertype
method
The correct method signature would be this public void onSuccess(int statusCode, Header[] headers, JSONObject response) or any of the other available methods in the JsonHttpResponseHandler class