Skip to content Skip to sidebar Skip to footer

Okhttp Put Example

My requirement is to use PUT, send a header and a body to server which will update something in the database. I just read okHttp documentation and I was trying to use their POST ex

Solution 1:

Change your .post with .put

publicvoidputRequestWithHeaderAndBody(String url, String header, String jsonBody) {


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

        OkHttpClient client = newOkHttpClient();

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

        makeCall(client, request);
    }

Solution 2:

OkHttp Version 2.x

If you're using OkHttp Version 2.x, use the following:

OkHttpClientclient=newOkHttpClient();

RequestBodyformBody=newFormEncodingBuilder()
        .add("Key", "Value")
        .build();

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

Responseresponse= client.newCall(request).execute();

if (!response.isSuccessful()) {
    thrownewIOException("Unexpected response code: " + response);
}

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

OkHttp Version 3.x

As OkHttp version 3 replaced FormEncodingBuilder with FormBody and FormBody.Builder(), for versions 3.x you have to do the following:

OkHttpClientclient=newOkHttpClient();

RequestBodyformBody=newFormBody.Builder()
        .add("message", "Your message")
        .build();

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

try {
    Responseresponse= client.newCall(request).execute();

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

Solution 3:

Use put method instead of post

Requestrequest=newRequest.Builder()
            .url(url)
            .put(body) // here we use put
            .addHeader("Authorization", header)
            .build();

Post a Comment for "Okhttp Put Example"