HttpClient连接https网站

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.ResourceBundle;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import javazoom.jl.player.Player;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;

public class Monitor {

private static ResourceBundle p = ResourceBundle.getBundle("Config");

public static void main(String[] args) {
int interval = Integer.valueOf(p.getString("interval"));
String do_url = p.getString("do_url");
String pharmweb_url = p.getString("pharmweb_url");
String do_login_url = p.getString("do_login_url");
String pharmweb_login_url = p.getString("pharmweb_login_url");
int timeout = Integer.valueOf(p.getString("timeout"));

String proxyAddress = p.getString("proxy");
int port = Integer.valueOf(p.getString("port"));

String musicPath = p.getString("music_path");

int sendmailCount = Integer.valueOf(p
.getString("sendmail_interrupt_count"));
int existCount = Integer.valueOf(p.getString("exit_interrupt_count"));

ScheduledExecutorService service = Executors
.newSingleThreadScheduledExecutor();
Task task = new Task(do_url, do_login_url, pharmweb_url,
pharmweb_login_url, timeout, proxyAddress, port, musicPath,
sendmailCount, existCount);
service.scheduleWithFixedDelay(task, 0, interval, TimeUnit.SECONDS);
}
}

class Task implements Runnable {
private static final SimpleDateFormat sf = new SimpleDateFormat(
"dd/MM/yyyy HH:mm:ss");

private String do_url ;
private String pharmweb_url ;
private String do_login_url ;
private String pharmweb_login_url ;
private int timeout = 30;
private String proxyAddress = "proxy1.scig.gov.hk";
private int port = 8080;
private String music;
private int sendmailCount;
private int existCount;

private static HashMap<String, Integer> interruptCounter = new HashMap<String, Integer>();
private static int totalErrorConnection = 0;

public Task(String do_url, String do_login_url, String pharmweb_url,
String pharmweb_login_url, int timeout, String proxyAddress,
int port, String music, int sendmailCount, int existCount) {
this.do_url = do_url;
this.do_login_url = do_login_url;
this.pharmweb_url = pharmweb_url;
this.pharmweb_login_url = pharmweb_login_url;
this.timeout = timeout;
this.proxyAddress = proxyAddress;
this.port = port;
this.music = music;
this.sendmailCount = sendmailCount;
this.existCount = existCount;
}

@Override
public void run() {
System.out.printf("=============== %s =====================\n", sf
.format(new Date()));

boolean useProxy = false;
if (!"".equals(this.proxyAddress)) {
useProxy = true;
}

System.out.printf("connect: %s\n", do_url);
if (connectionChecking(do_url, useProxy)) {
System.out.printf("connect: %s\n", do_login_url);
checkDoLogin(do_login_url, useProxy);
}

System.out.printf("connect: %s\n", pharmweb_url);
if (connectionChecking(pharmweb_url, false)) {
System.out.printf("connect: %s\n", pharmweb_login_url);
checkPharmwebLogin(pharmweb_login_url);
}

if (totalErrorConnection > 0) {
System.out.printf("total error connection: [%s]\n",
totalErrorConnection);
if (totalErrorConnection > this.existCount) {
System.exit(0);
}
}

System.out.println("\n");
notifyUser();
}

private void notifyUser() {
for (String url : interruptCounter.keySet()) {
int connectErrors = interruptCounter.get(url);

if (connectErrors > this.sendmailCount) {
System.out.println("send mail to notify users. error url: "
+ url);
interruptCounter.put(url, 0);
}
}
}

private boolean connectionChecking(String url, boolean useProxy) {
DefaultHttpClient client = new DefaultHttpClient();
if (useProxy) {
HttpHost proxy = new HttpHost(proxyAddress, port);
client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
proxy);
}
client.getParams().setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);

HttpGet httpget = new HttpGet(url);

try {
HttpResponse response = client.execute(httpget);
System.out.println(response.getStatusLine());
return true;
} catch (ClientProtocolException e) {
processException(url, e);
} catch (IOException e) {
processException(url, e);
} finally {
postProcess(client, url);
}
return false;
}

private void checkPharmwebLogin(String url) {
final DefaultHttpClient client = new DefaultHttpClient();
client.getParams().setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);

HttpPost httpget = new HttpPost(url);

try {
HttpResponse response = client.execute(httpget);
System.out.println(response.getStatusLine());
} catch (ClientProtocolException e) {
processException(url, e);
} catch (IOException e) {
processException(url, e);
} finally {
postProcess(client, url);
}
}

private void checkDoLogin(String url, boolean useProxy) {
HttpClient client = WebClientDevWrapper
.wrapClient(new DefaultHttpClient());
HttpPost httpget = new HttpPost(url);

try {
if (useProxy) {
HttpHost proxy = new HttpHost(proxyAddress, port);
client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
proxy);
}
client.getParams().setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
HttpResponse response = client.execute(httpget);
System.out.println(response.getStatusLine());

EntityUtils.consume(response.getEntity());
} catch (ClientProtocolException e) {
processException(url, e);
} catch (IOException e) {
processException(url, e);
} finally {
postProcess(client, url);
}
}

private void processException(String url, Exception e) {
e.printStackTrace();
System.out.printf("connect error:[%s]\n ", url);
try {
InputStream in = new FileInputStream(music);
Player player = new Player(in);
player.play();
} catch (Exception e1) {
e1.printStackTrace();
}

int num = 1;
if (interruptCounter.containsKey(url)) {
num = interruptCounter.get(url);
num++;
interruptCounter.put(url, num);
} else {
interruptCounter.put(url, num);
}
System.out.printf("url [%s] interrupt:[%d] \n", url, num);
totalErrorConnection++;
}

private void postProcess(HttpClient client, String url) {
client.getConnectionManager().shutdown();
/*
* if (interruptCounter.containsKey(url)) { interruptCounter.put(url,
* 0); }
*/
}
}

class WebClientWrapper {
public static HttpClient wrapClient(HttpClient base) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException {
}

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

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

ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx,
SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = base.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
return new DefaultHttpClient(ccm, base.getParams());

} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}

参考:
http://javaskeleton.blogspot.com/2010/07/avoiding-peer-not-authenticated-with.html
http://javasight.net/2011/06/avoid-javax-net-ssl-sslpeerunverifiedexception/