OkHttpClient
基本使用步骤如下
- 构建客户端对象OkHttpClient
- 构建请求Request
- 生成Call对象
- Call发起请求(同步/异步)
import java.io.IOException;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class HttpRequest {public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");OkHttpClient client = new OkHttpClient();public String get(String url) throws IOException {Request request = new Request.Builder().url(url).build();Response response = client.newCall(request).execute();return response.body().string();}public String post(String url, String json) throws IOException {RequestBody body = RequestBody.create(JSON, json);Request request = new Request.Builder().url(url).post(body).build();/* Call call = client.newCall(request);call.*/Response response = client.newCall(request).execute();return response.body().string();}public static void main(String[] args) throws IOException {HttpRequest request = new HttpRequest();System.out.println(request.get("http://www.baidu.com"));}}
加上忽略https证书验证,代码如下:
import okhttp3.*;import javax.net.ssl.*;
import java.io.IOException;public class HttpRequest {public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");// static OkHttpClient client = new OkHttpClient();//下面是跳过https网站证书验证的,我直接复制的public static OkHttpClient getUnsafeOkHttpClient() {try {final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {@Overridepublic void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {}@Overridepublic void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {}@Overridepublic java.security.cert.X509Certificate[] getAcceptedIssuers() {return new java.security.cert.X509Certificate[]{};}}};final SSLContext sslContext = SSLContext.getInstance("SSL");sslContext.init(null, trustAllCerts, new java.security.SecureRandom());final javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();OkHttpClient.Builder builder = new OkHttpClient.Builder();builder.sslSocketFactory(sslSocketFactory);builder.hostnameVerifier(new HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {return true;}});return builder.build();} catch (Exception e) {throw new RuntimeException(e);}}public String get(String url) throws IOException {Request request = new Request.Builder().url(url).build();OkHttpClient client = getUnsafeOkHttpClient();Response response = client.newCall(request).execute();return response.body().string();}public String post(String url, String json) throws IOException {RequestBody body = RequestBody.create(JSON, json);Request request = new Request.Builder().url(url).post(body).build();OkHttpClient client = getUnsafeOkHttpClient();Response response = client.newCall(request).execute();return response.body().string();}}