工具类
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import javax.net.ssl.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Random;
/**
* Created by WJY on 2017/5/5.
*/
public class OkHttpClientUtil {
/**
* 创建忽略SSL证书的OkHttpClient
* @return
*/
public static OkHttpClient buildSSLClient(){
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
};
ctx.init(null, new TrustManager[]{tm}, new java.security.SecureRandom());
SSLSocketFactory ssf = ctx.getSocketFactory();
return new OkHttpClient.Builder().sslSocketFactory(ssf,tm).hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
}).build();
}catch (Exception e){
e.printStackTrace();
}
return null;
}
private static String[] USER_AGENTS = {
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:16.0) Gecko/20100101 Firefox/16.0",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11",
"Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10" };
/**
* 随机返回一个UserAgent信息
*/
public static String getRandUserAgent(){
Random rd = new Random();
return USER_AGENTS[rd.nextInt(USER_AGENTS.length)];
}
/**
* 随机返回一个带有UserAgnet的header
* @return
*/
public static Headers randomUserAgent(){
return new Headers.Builder().add("User-Agent",getRandUserAgent()).build();
}
}
同步GET访问HTTPS页面方法
@Test
public void getHttpsPageTest() throws Exception {
OkHttpClient client = OkHttpClientUtil.buildSSLClient();
Request request = new Request.Builder()
.url("https://httpbin.org/get?username=zhangsan")
.build();
Call call = client.newCall(request);
try{
Response response = call.execute();
System.out.println(response.code());
System.out.println(response.body().string());
}catch (Exception e){
e.printStackTrace();
}
}
同步POST提交HTTPS页面方法
@Test
public void postHttpsPageTest() throws Exception {
OkHttpClient client = OkHttpClientUtil.buildSSLClient();
String url = "https://httpbin.org/post";
String postBody = ""
+ "Releases\n"
+ "--------\n"
+ "\n"
+ " * _1.0_ May 6, 2013\n"
+ " * _1.1_ June 15, 2013\n"
+ " * _1.2_ August 11, 2013\n";
Headers headers = OkHttpClientUtil.randomUserAgent();
Request request = new Request.Builder()
.post(RequestBody.create(MediaType.parse("text/x-markdown"),postBody))
.url(url)
.headers(headers)
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
}
异步GET访问方法
@Test
public void getAsync() throws Exception {
OkHttpClient client = OkHttpClientUtil.buildSSLClient();
Request request = new Request.Builder()
.url("https://httpbin.org/get?username=zhangsan")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println("失败!");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if(!response.isSuccessful()) System.out.println("出错");
else{
Headers responseHeaders = response.headers();
for (int i = 0; i < responseHeaders.size(); i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println(response.body().string());
}
}
});
System.out.println("开始访问===>");
//休眠5秒用于访问网页
Thread.sleep(10_000);
}
异步POST提交HTTPS页面方法
@Test
public void postAsync() throws Exception {
OkHttpClient client = OkHttpClientUtil.buildSSLClient();
String url = "https://httpbin.org/post";
String postBody = ""
+ "Releases\n"
+ "--------\n"
+ "\n"
+ " * _1.0_ May 6, 2013\n"
+ " * _1.1_ June 15, 2013\n"
+ " * _1.2_ August 11, 2013\n";
Headers headers = OkHttpClientUtil.randomUserAgent();
Request request = new Request.Builder()
.post(RequestBody.create(MediaType.parse("text/x-markdown"),postBody))
.url(url)
.headers(headers)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println("失败!");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if(!response.isSuccessful()) System.out.println("出错");
else{
Headers responseHeaders = response.headers();
for (int i = 0; i < responseHeaders.size(); i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println(response.body().string());
}
}
});
System.out.println("开始访问===>");
//休眠5秒用于访问网页
Thread.sleep(10_000);
}
最后编辑时间为: May 5th , 2017 at 03:31 pm
本文由
wjy 创作,采用
知识共享署名 4.0 国际许可协议进行许可
可自由转载、引用,但需署名作者且注明文章出处