Table of Contents
okhttpclient get/post/form requests example:
Maven dependency:
[xml]
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.11.0</version>
</dependency>
[/xml]
okhttpclient with formbody example:
[java]
public class App
{
public static void main( String[] args ) throws IOException
{
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormBody.Builder()
.add(“client_id”, “some_value”)
.add(“client_secret”, “some_value”)
.build();
Request request = new Request.Builder()
.url(“some_url”)
.post(formBody)
.addHeader(“authorization”, “headers_here”)
.addHeader(“cache-control”, “no-cache”)
.build();
Response response = client.newCall(request).execute();
System.out.println(“response => “+response);
}
}
[/java]
okhttpclient with multipart form data request example:
[java]
public class App
{
public static void main( String[] args ) throws IOException
{
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart(“client_id”, “some_value”)
.addFormDataPart(“scope”, “some_value”)
.build();
Request request = new Request.Builder()
.url(“some_url”)
.post(requestBody )
.addHeader(“authorization”, “headers_here”)
.addHeader(“cache-control”, “no-cache”)
.build();
Response response = client.newCall(request).execute();
System.out.println(“response => “+response);
}
}
[/java]
okhttpclient with get request example:
[java]
public class App
{
public static void main( String[] args ) throws IOException
{
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(“some_url”)
.get()
.addHeader(“authorization”, “headers_here”)
.addHeader(“cache-control”, “no-cache”)
.build();
Response response = client.newCall(request).execute();
System.out.println(“response => “+response);
}
}
[/java]