How to make a POST request using retrofit 2?
Solution 1
If you don't want JSON encoded params use this:
@FormUrlEncoded
@POST("/")
Call<ApiResponse> request(@Field("api_key") String apiKey, @Field("app_id") String appId);
Solution 2
You should be aware of how you want to encode the post params. Important is also the @Header
annotation in the following. It is used to define the used content type in the HTTP header.
@Headers("Content-type: application/json")
@POST("user/savetext")
public Call<Id> changeShortText(@Body MyObjectToSend text);
You have to encode your post params somehow. To use JSON for transmission you should add .addConverterFactory(GsonConverterFactory.create(gson))
into your Retrofit 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 could be that the JSON, that's coming from the rest backend seems to be not correct. You should check the json syntax with a validator, e.g. http://jsonlint.com/.
Cool Do
Updated on July 09, 2022Comments
-
Cool Do almost 2 years
I was only able to run the hello world example (GithubService) from the docs.
The problem is when I run my code, I get the following Error, inside of
onFailure()
Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $
My API takes POST params value, so no need to encode them as JSON, but it does return the response in JSON.
For the response I got ApiResponse class that I generated using tools.
My interface:
public interface ApiService { @POST("/") Call<ApiResponse> request(@Body HashMap<String, String> parameters); }
Here 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------"); } });
-
Cool Do over 8 years
@Header not applicable to method
so cannot compile, I dont want to encode to json , just post raw values -
Veeresh Charantimath over 7 yearsCorrection - @Headers("Content-type: application/json")
-
GvSharma over 5 yearshow to call post method with params here?