OkHttp is an excellent HTTP+HTTP/2 client for Square Open source, which works on Android and Java platforms.
Website Introduction Original
An HTTP+HTTP/2 client for Android and Java applications. http://square.github.io/okhttp/ API Example
Add Maven dependencies, as follows:
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactid>okhttp</ artifactid>
<version>3.4.1</version>
</dependency>
1. Get Request
Okhttpclient client = new Okhttpclient ();
String run (string url) throws IOException {
Request request = new Request.builder ()
. URL (URL)
. Build ();
Response Response = client.newcall (Request). Execute ();
Return Response.body (). String ();
}
2. Post Request
public static final mediatype JSON
= Mediatype.parse ("Application/json; Charset=utf-8 ");
Okhttpclient client = new Okhttpclient ();
String post (string URL, string json) throws IOException {
Requestbody BODY = requestbody.create (JSON, JSON);
Request Request = new Request.builder ()
. URL (URL).
post (body)
. Build ();
Response Response = client.newcall (Request). Execute ();
Return Response.body (). String ();
}
3. Post form submission
Okhttpclient client = new Okhttpclient ();
String post (string url, list<formparam> params) throws IOException {
Formbody.builder Builder = new Formbody.bu Ilder ();
for (Formparam param:params) {
builder.addencoded (Param.getname (), Param.getvalue ());
}
Request Request = new Request.builder ()
. URL (URL).
post (Builder.build ())
. Build ();
Response Response = client.newcall (Request). Execute ();
Return Response.body (). String ();
}
4. File Upload
import okhttp3.*;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
/**
* ${DESCRIPTION}
*
* @author Ricky Fung
* @create 2016-11-17 15:16
*/
public class FileUploadTest {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.build();
public void upload(String url, File file) throws IOException {
RequestBody formBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", file.getName(),
RequestBody.create(MediaType.parse("text/plain"), file))
.addFormDataPart("field1", "field1_value")
.build();
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
Response response = this.client.newCall(request).execute();
}
}
Best Practices
Okhttp The official Doc recommends creating only one Okhttpclient sample object to handle all HTTP requests.
Original website:
Okhttpclients should be shared
OkHttp performs best if you create a single okhttpclient instance and reuse it for all of the your HTTP calls. This is because each client holds its own connection pool and thread pools. Reusing connections and threads reduces latency and saves memory. Conversely, creating a client for each request wastes resources on idle pools. okhttpclient Construction
1. Create a shared instance with the default settings:
The singleton HTTP client.
Public final Okhttpclient client = new Okhttpclient ();
2. Create a shared instance with custom settings:
The singleton HTTP client.
Public final Okhttpclient client = new Okhttpclient.builder ()
. ReadTimeout (6000,timeunit.milliseconds)
. ConnectTimeout (6000, timeunit.milliseconds)
. Addinterceptor (New Httplogginginterceptor ())
. Cache (New Cache (Cachedir, cacheSize))
. Build ();
Okhttp Package Class
Usually in development often need to deal with HTTP requests, so their own Apache HttpClient, OkHttp, Asynchttpclient Unified to do the package, here only show the package of OkHttp, the code is as follows:
Okhttpclientimpl class
package com.bytebeats.toolkit.http.impl;
import com.bytebeats.toolkit.annotation.ThreadSafe;
import com.bytebeats.toolkit.http.HttpRequestException;
import com.bytebeats.toolkit.http.config.FormParam;
import com.bytebeats.toolkit.http.config.HttpRequestConfig;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* OkHttp实现
* https://square.github.io/okhttp/3.x/okhttp/okhttp3/OkHttpClient.html
*
* @author Ricky Fung
* @create 2016-08-23 12:17
*/
@ThreadSafe
public class OkHttpClientImpl extends HttpClient {
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
private final Logger logger = LoggerFactory.getLogger(OkHttpClientImpl.class);
private OkHttpClient client;
public OkHttpClientImpl(HttpRequestConfig config) {
super(config);
ConnectionPool connectionPool = new ConnectionPool(5, 5, TimeUnit.SECONDS);
client = new OkHttpClient.Builder()
.readTimeout(this.config.getReadTimeout(), TimeUnit.MILLISECONDS)
.connectTimeout(this.config.getConnectTimeout(), TimeUnit.MILLISECONDS)
.connectionPool(connectionPool)
.retryOnConnectionFailure(false)
.build();
}
@Override
public String get(String url) throws HttpRequestException {
Request request = createGetRequest(url);
Response response = execute(request);
try {
return convertResponseBodyToString(response.body());
}catch (IOException e) {
logger.error("OkHttp getAsBytes error", e);
throw new HttpRequestException("OkHttp getAsBytes error", e);
}
}
@Override
public byte[] getBytes(String url) throws HttpRequestException {
Request request = createGetRequest(url);
Response response = execute(request);
try {
return convertResponseBodyToBytes(response.body());
} catch (IOException e) {
logger.error("OkHttp getAsBytes error", e);
throw new HttpRequestException("OkHttp getAsBytes error", e);
}
}
@Override
public String postWithForm(String url, List<FormParam> params) throws HttpRequestException {
Request request = createPostForm(url, params);
Response response = execute(request);
try {
return convertResponseBodyToString(response.body());
}catch (IOException e) {
logger.error("OkHttp postWithForm error", e);
throw new HttpRequestException("OkHttp postWithForm error", e);
}
}
@Override
public byte[] postWithFormBytes(String url, List<FormParam> params) throws HttpRequestException {
Request request = createPostForm(url, params);
Response response = execute(request);
try {
return convertResponseBodyToBytes(response.body());
}catch (IOException e) {
logger.error("OkHttp postWithForm error", e);
throw new HttpRequestException("OkHttp postWithForm error", e);
}
}
@Override
public String postWithBody(String url, String json) throws HttpRequestException {
Request request = createPostBody(url, json);
Response response = execute(request);
try {
return convertResponseBodyToString(response.body());
}catch (IOException e) {
logger.error("OkHttp getAsBytes error", e);
throw new HttpRequestException("OkHttp getAsBytes error", e);
}
}
@Override
public byte[] postWithBodyBytes(String url, String json) throws HttpRequestException {
Request request = createPostBody(url, json);
Response response = execute(request);
try {
return convertResponseBodyToBytes(response.body());
} catch (IOException e) {
logger.error("OkHttp postAsBytes error", e);
throw new HttpRequestException("OkHttp postAsBytes error", e);
}
}
private Response execute(Request request) throws HttpRequestException {
try{
return client.newCall(request).execute();
}catch (Exception e){
logger.error("OkHttp post error", e);
throw new HttpRequestException("OkHttp post error", e);
}
}
private String convertResponseBodyToString(ResponseBody responseBody) throws IOException {
if(responseBody!=null){
return responseBody.string();
}
return null;
}
private byte[] convertResponseBodyToBytes(ResponseBody responseBody) throws IOException {
if(responseBody!=null){
return responseBody.bytes();
}
return null;
}
private Request createPostForm(String url, List<FormParam> params){
FormBody.Builder builder = new FormBody.Builder();
for(FormParam param : params){
builder.addEncoded(param.getName(), param.getValue());
}
Request request = new Request.Builder()
.url(url)
.post(builder.build())
.build();
return request;
}
private Request createPostBody(String url, String json){
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
return request;
}
private Request createGetRequest(String url){
Request request = new Request.Builder()
.url(url)
.build();
return request;
}
}
Formparam class
Package com.bytebeats.toolkit.http.config;
/**
* ${description}
*
* @author Ricky Fung
* @create 2016-08-24 16:17
*/public class Formparam {
private final String name;
Private final String value;
Public Formparam (string name, String value) {
this.name = name;
This.value = value;
}
Public String GetName () {
return this.name;
}
Public String GetValue () {
return this.value;
}
}
References
Okhttp Official website: http://square.github.io/okhttp/
OkHttp Recipes:https://github.com/square/okhttp/wiki/recipes
Okhttpclient doc:https://square.github.io/okhttp/3.x/okhttp/okhttp3/okhttpclient.html