Android:如何使用okhttp3发送带有效负载参数的PUT请求

时间:2018-03-12 22:49:52

标签: android okhttp3

我已经尝试了许多不同的方法来使用okhttp3发送带有效负载的PUT请求,但是没有一个可以工作,任何人都可以告诉我如何使用okhttp3来完成这项工作吗?我只是粘贴Chrome浏览器中的一些关键标题信息。

    General:
    Request URL:http://8.102.239.245/abc/api/108/actions?name=Rename
    Request Method:PUT

    Request Headers: 
    Content-Type:application/json;charset=UTF-8

    Query String Parameters: 
    name:Rename

    Request Payload: 
    {id: 108, name: "dbd"}

1 个答案:

答案 0 :(得分:0)

我建议添加Retrofit以便于API定义:

compile 'com.squareup.retrofit2:retrofit:2.1.0'

添加后,请执行以下操作:

  1. 将接口和您的请求定义为方法:

    public interface MyService {
        @PUT("abc/api/{id}/actions")
        Call<YourResponse> putName(@Path("id") int id, @Query("name") String name);
    }
    
  2. 使用OkHttpClient实例化您的API:

     MyService myService = okHttpClient.create(MyService.class)
    
  3. 发出您的请求:

    Call<YourResponse> call = myService.putName(108, "Rename");
    call.enqueue(new Callback<YourResponse>() { ... };