如何使用改造2发出POST请求? [英] How to make a POST request using retrofit 2?

查看:87
本文介绍了如何使用改造2发出POST请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只能从文档中运行hello world示例(GithubService).

I was only able to run the hello world example (GithubService) from the docs.

问题是当我运行代码时,在onFailure()

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

使用JsonReader.setLenient(true)在第1行接受格式错误的JSON 第1列路径$

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

我的API采用POST参数值,因此无需将其编码为JSON,但确实会以JSON返回响应.

My API takes POST params value, so no need to encode them as JSON, but it does return the response in JSON.

对于响应,我获得了使用工具生成的ApiResponse类.

For the response I got ApiResponse class that I generated using tools.

我的界面:

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

推荐答案

如果您不希望使用JSON编码的参数,请使用以下方法:

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

这篇关于如何使用改造2发出POST请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆