Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a JSON POST request using Retrofit in Android, and recieve a String response

I'm using Retrofit2 for the first time and have a few issues.

This is the code snippet used to call the REST API

    //building retrofit object
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://192.168.0.71:9000/api/uniapp/")
            .addConverterFactory(GsonConverterFactory.create())
            .addConverterFactory(ScalarsConverterFactory.create())
            .build();

    APIService service = retrofit.create(APIService.class);

    //defining the call
    Call<String> call = service.refreshAppMetaConfig("0");
    //calling the api
    call.enqueue(new Callback<String>() {
        @Override
        public void onResponse(Call<String> call, Response<String> response) {
            //displaying the message from the response as toast
            System.out.println("Uniapp :"+response);
        }

        @Override
        public void onFailure(Call<String> call, Throwable t) {
            System.out.println("Uniapp :"+t.getMessage());
        }
    });

This is the APIService class :

public interface APIService {

    //The register call
    @FormUrlEncoded
    @POST("appmetaconfigjson")
    Call<String> refreshAppMetaConfig(@Field("versionId") String versionId);
}

I'm using Play framework for creating the REST API. I am getting an internal server error. The API is not able to read the JSON request. But if I hit the API through Postman, it returns the response. Any suggestions?

Ive added the postman request screenshot.

Postman Sample

like image 705
Arjun Issar Avatar asked Oct 20 '25 17:10

Arjun Issar


1 Answers

As I can see from your screenshots of Postman, you're sending JSON body to REST API. When you select body type as raw - application/json in Postman, it automatically includes

Content-Type:application/json

as header. Hence, the request is successful in Postman.

Now, in order to make it work above request successfully in your Android application, you need to set headers with the request you send to REST API.

In APIService interface do the below changes.

import retrofit2.http.Body;
import okhttp3.ResponseBody;
import java.util.Map;


public interface APIService {

  //The register call
  // @FormUrlEncoded    <====  comment or remove this line

   @Headers({
        "Content-Type:application/json"
   })
   @POST("appmetaconfigjson")
   Call<ResponseBody> refreshAppMetaConfig(@Body Map<String, String> versionId);
}
  1. Remove or comment @FormUrlEncoded annotation as we're sending JSON not FormUrlEncoded data.
  2. Add @Headers() annotation with Content-Type:application/json
  3. Change method parameter to @Body Map<String, String> versionId. The @Body annotation converts (serializes) Map (HashMap) data into JSON body when you request to API.
  4. Change return parameter from String to ResponseBody.

Use the above-modified method as below

// code...

//defining the call

// create parameter with HashMap
Map<String, String> params = new HashMap<>();
params.put("versionId", "0");

Call<ResponseBody> call = service.refreshAppMetaConfig(params);
//calling the api
call.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        //displaying the message from the response as toast

        // convert ResponseBody data to String
        String data = response.body().string();

        System.out.println("Uniapp : " + data);
    }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        System.out.println("Uniapp : " + t.getMessage());
    }
});

Here also you need to change parameter from Call<String> to Call<ResponseBody>. And convert the response inside onResponse() method using response.body().string();.

like image 117
Shashanth Avatar answered Oct 22 '25 05:10

Shashanth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!