OKhttp PUT示例

时间:2016-01-19 20:18:13

标签: android retrofit okhttp android-networking androidhttpclient

我的要求是使用PUT,向服务器发送标题和正文,这将更新数据库中的内容。

我刚刚阅读okHttp documentation并尝试使用他们的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 个答案:

答案 0 :(得分:9)

使用.post

更改.put
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);
    }

答案 1 :(得分:3)

使用put方法代替post

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

答案 2 :(得分:2)

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将FormEncodingBuilder替换为FormBodyFormBody.Builder(),因此对于版本3.x,您必须执行以下操作:

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();
}