OKhttp的PUT请求示例

22

我的要求是使用PUT方法,向服务器发送一个头和一个主体,来更新数据库中的某些内容。

我刚阅读了okHttp文档,尝试使用他们的POST示例,但它不适用于我的用例(我认为这可能是因为服务器要求我使用PUT而不是POST

这是我使用POST的方法:

 public void postRequestWithHeaderAndBody(String url, String header, String jsonBody) {


        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, jsonBody);

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("Authorization", header)
                .build();

        makeCall(client, request);
    }

我尝试搜索使用PUT的okHttp示例,但没有成功,如果我需要使用PUT方法,有没有任何方法可以使用okHttp?

我正在使用okhttp:2.4.0(以防万一),感谢任何帮助!

3个回答

13

使用.put替换您的.post

public void putRequestWithHeaderAndBody(String url, String header, String jsonBody) {


        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, jsonBody);

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(url)
                .put(body) //PUT
                .addHeader("Authorization", header)
                .build();

        makeCall(client, request);
    }

如果请求没有主体,也就是说如何在不使用请求主体的情况下使用OKHttp发送PUT请求? - B.shruti

5

OkHttp 2.x版本

如果您正在使用OkHttp 2.x版本,请使用以下内容:

OkHttpClient client = new OkHttpClient();

RequestBody formBody = new FormEncodingBuilder()
        .add("Key", "Value")
        .build();

Request request = new Request.Builder()
    .url("http://www.foo.bar/index.php")
    .put(formBody)  // Use PUT on this line.
    .build();

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

if (!response.isSuccessful()) {
    throw new IOException("Unexpected response code: " + response);
}

System.out.println(response.body().string());

OkHttp 版本 3.x

在 OkHttp 3.x 版本中,FormEncodingBuilderFormBodyFormBody.Builder() 替代。因此,您需要按照以下方式进行操作:

OkHttpClient client = new OkHttpClient();

RequestBody formBody = new FormBody.Builder()
        .add("message", "Your message")
        .build();

Request request = new Request.Builder()
        .url("http://www.foo.bar/index.php")
        .put(formBody) // PUT here.
        .build();

try {
    Response response = client.newCall(request).execute();

    // Do something with the response.
} catch (IOException e) {
    e.printStackTrace();
}

3

使用put方法代替post方法。

Request request = new Request.Builder()
            .url(url)
            .put(body) // here we use put
            .addHeader("Authorization", header)
            .build();

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