How to make a POST request using modification 2?

I was able to run only the welcome example (GithubService) from the documentation.

The problem is that when I run my code, I get the following error inside onFailure()

Use JsonReader.setLenient (true) to accept invalid JSON in row 1 column 1 path $

My API accepts the value of the POST parameter, so there is no need to encode them as JSON, but it returns the response in JSON.

For the answer, I got the ApiResponse class, which I generated using the tools.

My interface:

 public interface ApiService { @POST("/") Call<ApiResponse> request(@Body HashMap<String, String> parameters); } 

This is how I use the service:

 HashMap<String, String> parameters = new HashMap<>(); parameters.put("api_key", "xxxxxxxxx"); parameters.put("app_id", "xxxxxxxxxxx"); Call<ApiResponse> call = client.request(parameters); call.enqueue(new Callback<ApiResponse>() { @Override public void onResponse(Response<ApiResponse> response) { Log.d(LOG_TAG, "message = " + response.message()); if(response.isSuccess()){ Log.d(LOG_TAG, "-----isSuccess----"); }else{ Log.d(LOG_TAG, "-----isFalse-----"); } } @Override public void onFailure(Throwable t) { Log.d(LOG_TAG, "----onFailure------"); Log.e(LOG_TAG, t.getMessage()); Log.d(LOG_TAG, "----onFailure------"); } }); 
+7
java android post retrofit retrofit2
source share
2 answers

If you do not want the encoded JSON parameters to use this:

 @FormUrlEncoded @POST("/") Call<ApiResponse> request(@Field("api_key") String apiKey, @Field("app_id") String appId); 
+9
source share

You need to know how you want to code the post parameters. Important is also the @Header annotation in the following. It is used to determine the type of content used in the HTTP header.

 @Headers("Content-type: application/json") @POST("user/savetext") public Call<Id> changeShortText(@Body MyObjectToSend text); 

You must somehow encode your parameters. To use JSON for transmission, you must add .addConverterFactory(GsonConverterFactory.create(gson)) in your update declaration.

 Retrofit restAdapter = new Retrofit.Builder() .baseUrl(RestConstants.BASE_URL) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create(gson)) .client(httpClient) .build(); 

Another source of your problem might be that the JSON that comes from the rest of the backend seems wrong. You should check json syntax with validator e.g. http://jsonlint.com/ .

+2
source share

All Articles