如何使用Retrofit发布(x-www-form-urlencoded)Json数据?

4
当我在Postman中以body (x-www-form-urlencoded)的形式发布数据时,可以正常工作。但是在使用Retrofit 2.0 Android时却无法正常工作。
@Headers("Content-Type: application/x-www-form-urlencoded")
@POST("/api/jsonws/pushUserData")
Call<ResponseBody>  pushData(@Body JSONObject jsonObj);

JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("role","owner");
            jsonObject.put("id","27001");

        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiInterface apiInterface1= ApiClient.getClientAuthentication().create(ApiInterface.class);
        Call<ResponseBody> responseBodyCall = apiInterface1.pushData(jsonObject);

这段代码不起作用。我也尝试了 @FormUrlEncoded。

你会从https://dev59.com/2VkR5IYBdhLWcg3w0AKy获取帮助。 - Rahul Chaudhary
1个回答

11
尝试使用 @FormUrlEncoded 并使用 @Field 替代 @Body
@FormUrlEncoded
@POST("/api/jsonws/pushUserData")
Call<ResponseBody>  pushData(@Field("role") String role, @Field("id") String id);

ApiInterface apiInterface1= ApiClient.getClientAuthentication().create(ApiInterface.class);
Call<ResponseBody> responseBodyCall = apiInterface1.pushData("owner","27001");

java.lang.IllegalArgumentException: @Body参数不能与表单或多部分编码一起使用。(参数#1)。应用程序已崩溃。 - Kamal Kakkar
请使用@Field代替@Body,请查看更新的答案。 - Navneet Krishna
1
谢谢,现在它可以正常工作了。 - Kamal Kakkar
1
但是如果我使用@Field,则特殊字符会在数据中进行编码。 - SAM

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接