【问题标题】:Sending form-data with retrofit2使用 retrofit2 发送表单数据
【发布时间】:2017-06-02 07:41:18
【问题描述】:

我有一个端点,我在其中放置一些数据,其中 Content-Type 应该是表单数据。

我正在使用

 @FormUrlEncoded
 @PUT("/api/v1/clients/profile/all_details")
 Call<ResponseBody> postUserProfile(@FieldMap Map<String, String> userParams);

但是在发送请求时,表单数据被编码为

food_allergy=%5Beggs%2C%20milk%2C%20nuts%2C%20none%5D&diet_prefer=Non%20Vegetarian&age=25&exercise_level=Moderate&email=Email&name=Veeresh&height=175&prompt-qgreet3=I%27m%20ready%21&gender=Female&health_condition=%5Bdiabetes%2C%20PCOD%5D&weight=69

如何删除编码?

我试过这个博客

https://futurestud.io/tutorials/retrofit-send-data-form-urlencoded-using-fieldmap

【问题讨论】:

  • 编写一个正则表达式,它开始检查 % 作为第一项和 & 作为最后一项。
  • 还有其他替代正则表达式的方法吗?

标签: android retrofit2


【解决方案1】:

您可以首先使用替换所有 %

string.replace("%","");

然后以同样的方式完成其余的操作。

【讨论】:

    【解决方案2】:

    如果你不想对表单数据进行编码,那么你可以这样尝试

    @PUT("/api/v1/clients/profile/all_details") Call<ResponseBody> postUserProfile(@QueryMap Map<String, String> userParams);

    编辑 1

    @Multipart
            @PUT("/api/v1/clients/profile/all_details")
            Call<ResponseBody> postUserProfile(@Part(username) RequestBody username, @Part(password) RequestBody password);
    

    下面是如何从 String 中获取 requestBody。

    String username = "username";
    RequestBody body = RequestBody.create(MediaType.parse("text/plain"), username);
    
    String password = "password";
    RequestBody body = RequestBody.create(MediaType.parse("text/plain"), password);
    

    【讨论】:

    • 不,它不能是@QueryMap,QueryMap 可以添加到 url 中
    • @Part 中使用的密钥是动态的,我无法对其进行硬编码
    • 那你可以用@PartMap() Map&lt;String, RequestBody&gt; partMap代替@Part
    【解决方案3】:

    @FieldMap 有一个名为encoded 的元素,默认为false

    如果您将其设置为true,则表示我的数据已经编码,我不希望Retrofit 处理编码。

    @FieldMap(encoded = true) Map&lt;String, String&gt; userParams

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-24
      • 2014-03-06
      • 2020-02-04
      • 1970-01-01
      相关资源
      最近更新 更多