OkHttp Cheatsheet

OkHttp Cheatsheet

OkHttp Cheatsheet

OkHttp is the network library so far which I have been using in my projects.
from android application to desktop apps. I this post I am sharing the code snippet which I have used in my projects.

Include the library in your project. I mainly use gradle for my projects.

//in build.gradle file include the dependency  

1. Initalise the client

OkHttpClient  client = new OkHttpClient().newBuilder()
        .readTimeout(60, TimeUnit.SECONDS) //set the read timeout
        .connectTimeout(60, TimeUnit.SECONDS) //set the connect timeout
client.dispatcher().setMaxRequests(Integer.MAX_VALUE); //set the maximum request
client.dispatcher().setMaxRequestsPerHost(Integer.MAX_VALUE); //set the maximum request per host

2. Simple Get Requests

//get Requests
Request request = new Request.Builder().url("https://www.google.com").get()
Response getResponse =  client.newCall(request).execute();
String getResponseBody =  getResponse.body().string();
System.out.println("get Response body "+getResponseBody);
getResponse.close(); //Important to close the response or else it will cause memory leak

3. Post JSON Request

//Post JSON Request
//create media type
MediaType MediaType_JSON = MediaType.parse("application/json; charset=utf-8");
//create post body
RequestBody postRequestBody = RequestBody.create(Global.MediaType_JSON, "{jsondata:\"data\"}");
//create request
Request postRequest = new Request.Builder().url("http://localhost:3000/dattopost")
//send request
Response postResponse =  client.newCall(request).execute();

4. Post form-data

//Post form data
//create form body
FormBody.Builder formBody = new FormBody.Builder();
formBody.add("j_username", "userName")
        .add("j_password", "Password")
        .add("remember-me", "false")
        .add("submit", "Login");
//create form request body
RequestBody formRequestBody = formBody.build();
//create request
Request formRequest = new Request.Builder().url("http://localhost:3000/auth")
        .method("POST", formRequestBody)
//send the request
Response formResponse =  client.newCall(request).execute();

5. Upload file (here zip file is uploaded to the server)

//create request body
//here replace "file" with your parameter name
//Change media type according to your file type
RequestBody fileRequestBody = new MultipartBody.Builder()
        .addFormDataPart("file", zipFile.getName(),
                RequestBody.create(MediaType.parse("application/zip"), zipFile))
//create the request
Request fileRequest = new Request.Builder().url("http://localhost:3000/upload")
//send the request
Response fileResponse =  client.newCall(fileRequest).execute();

6. Modify headers

Request request = new Request.Builder().url("https://www.google.com")
        .addHeader("X-XSRF-TOKEN", "Token value") //add headers