OKhttp PUT example
Change your .post
with .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); }
OkHttp Version 2.x
If you're using OkHttp Version 2.x, use the following:
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 Version 3.x
As OkHttp version 3 replaced FormEncodingBuilder
with FormBody
and FormBody.Builder()
, for versions 3.x you have to do the following:
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();}