如何在 Android 中使用 Retrofit 发送 JSON POST 请求,并接收字符串响应

Arj*_*sar 3 post android json playframework retrofit2

我是第一次使用 Retrofit2,遇到了一些问题。

这是用于调用 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());
        }
    });
Run Code Online (Sandbox Code Playgroud)

这是 APIService 类:

public interface APIService {

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

我正在使用 Play 框架来创建 REST API。我收到内部服务器错误。API 无法读取 JSON 请求。但是如果我通过 Postman 访问 API,它会返回响应。有什么建议?

我已经添加了邮递员请求截图。

邮递员样本

Sha*_*nth 5

正如我从您的 Postman 屏幕截图中看到的,您正在将 JSON 正文发送到 REST API。当您在 Postman 中选择体型为raw-application/json时,它会自动包括

Content-Type:application/json
Run Code Online (Sandbox Code Playgroud)

作为标题。因此,请求在 Postman 中成功。

现在,为了使其在您的 Android 应用程序中成功地处理请求,您需要使用发送到 REST API 的请求设置标头。

APIService界面中进行以下更改。

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);
}
Run Code Online (Sandbox Code Playgroud)
  1. 删除或注释@FormUrlEncoded注释,因为我们发送的是 JSON 而不是 FormUrlEncoded 数据。
  2. 添加@Headers()注释Content-Type:application/json
  3. 将方法参数更改为@Body Map<String, String> versionId. 当您向 API 请求时,该@Body注解会将 ( MapHashMap) 数据转换(序列化)为 JSON 正文。
  4. 将返回参数从 更改StringResponseBody

使用上面修改的方法如下

// 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());
    }
});
Run Code Online (Sandbox Code Playgroud)

在这里,您还需要将参数从 更改Call<String>Call<ResponseBody>。并onResponse()使用response.body().string();.