Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

java - How to make a POST request using retrofit 2?

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------");
    }
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...