使用okhttp访问ssl(https)网络

直接抄网上的示例,发现会证书认证失败:unable to find valid certification path to requested target
需要先配置SSLcontext和SSLSocketFactory。

直接上代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
try {
sslContext = SSLContext.getInstance("TLS");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}

TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}

@Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}

@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};

try {
sslContext.init(null, new TrustManager[] { tm }, null);
} catch (KeyManagementException e) {
e.printStackTrace();
}

javax.net.ssl.SSLSocketFactory factory = sslContext.getSocketFactory();

client.setSslSocketFactory(factory);

client.setHostnameVerifier(new HostnameVerifier() {

@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});

FormEncodingBuilder builder=new FormEncodingBuilder();
if (postContent != null && postContent.size() > 0) {
Iterator> i = postContent.entrySet().iterator();
while (i.hasNext()) {
Entry entry = i.next();
if (entry.getValue() == null) {
log.info("null -->" + entry.getKey());
continue;
}
builder.add(entry.getKey(), (String)entry.getValue());
}

RequestBody body = builder.build();

Request request = new Request.Builder().url(url).post(body).build();

Response response = client.newCall(request).execute();
//注意這裡,response.body().string()只能運行一次,response的內容只能取一次
sb = response.body().string();
System.out.println("sb is " + sb);