【问题标题】:send two string item as body in retrofit在改造中发送两个字符串项目作为正文
【发布时间】:2018-06-03 19:47:52
【问题描述】:

我有一个这样的改造对象:

retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

@Headers
({
    "Content-Type: application/x-www-form-urlencoded",
            "cache-control: no-cache"
})
@POST("login")
Call<RegisterResponse> register(@Body String n1,@Body String n2);

我知道这是不正确的,因为有两个正文注释。
所以我必须使用这段代码

@Headers
({
    "Content-Type: application/x-www-form-urlencoded",
            "cache-control: no-cache"
})
@POST("login")
Call<RegisterResponse> register(@Body TestObject testObject);

 class TestObject{
     String n1;
     String n2;

 }

但我有一个服务器,我无法更改它,它有两个参数作为正文。
当我使用邮递员时,我的服务器工作得很好,可以做应该做的事情。
但是当我使用改造时出现错误 500“服务器内部错误”
我已经用 okhttp 完成了这个

 HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
  interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
  OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();



  MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
  RequestBody body = RequestBody.create(mediaType, "n1=09369&n2=145616");
  Request request = new Request.Builder()
          .url(URL)
          .post(body)
          .addHeader("content-type", "application/x-www-form-urlencoded")
          .addHeader("cache-control", "no-cache")
          .addHeader("postman-token", "0761ac45-1fb7-78df-d088-2437ecb984a3")
          .build();

  okhttp3.Response response = client.newCall(request).execute();

它工作正常,但我如何通过改造来做到这一点?

【问题讨论】:

  • when I use postman my server works just fine 你到底是怎么用的?这两具尸体从哪里经过?
  • 在邮递员中我只有一个正文标签,我在其中添加了两个参数
  • 然后做同样的事情 - 在其中添加 2 个参数。没有设置body。

标签: android retrofit retrofit2


【解决方案1】:

您需要的是使用@FormUrlEncoded 注解发送数据,阅读更多信息here

你可以这样使用它:

@FormUrlEncoded
@POST("login")
Call<RegisterResponse> register(@Field("n1") String n1, @Field("n2") String n2);

【讨论】:

    【解决方案2】:

    需要稍作修改

    class TestObject{
         @SerializedName("n1")
         @Expose
         String n1;//if your server is looking for key with name n1, or change it to the required key
    
         @SerializedName("n2")
         @Expose
         String n2;
     }
    

    您的呼叫代码将与原来相同。

    希望这可能会有所帮助。:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-04
      • 1970-01-01
      • 2011-04-25
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      相关资源
      最近更新 更多