komal sharma
komal sharma

Reputation: 195

Not able to complete the Retrofit request?

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?

Upvotes: 2

Views: 170

Answers (1)

Fadils
Fadils

Reputation: 1526

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.

Upvotes: 1

Related Questions