HttpURLConnection是JDK提供的用于发送接收Http请求的类。不需要要引入第三方jar包即可使用,支持http和https的发送方式。
发送https需要的前置信息初始化
private static SSLContext ctx = null;
private static HostnameVerifier verifier = null;
private static SSLSocketFactory socketFactory = null;
private static class DefaultTrustManager implements X509TrustManager {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
}
static {
try {
ctx = SSLContext.getInstance("TLS");
ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() },
new SecureRandom());
ctx.getClientSessionContext().setSessionTimeout(15);
ctx.getClientSessionContext().setSessionCacheSize(1000);
socketFactory = ctx.getSocketFactory();
} catch (Exception e) {
e.printStackTrace();
}
verifier = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return false;//默认认证不通过,进行证书校验。
}
};
}
获取Connection:
private static HttpURLConnection getConnection(URL url, String method,
String ctype) throws IOException {
HttpURLConnection conn = null;
if ("https".equals(url.getProtocol())) {
HttpsURLConnection connHttps = (HttpsURLConnection) url.openConnection();
connHttps.setSSLSocketFactory(socketFactory);
connHttps.setHostnameVerifier(verifier);
conn = connHttps;
} else {
conn = (HttpURLConnection) url.openConnection();
}
conn.setRequestMethod(method);
conn.setDoInput(true);
conn.setDoOutput(true);
//设置请求头信息
conn.setRequestProperty("Accept", "text/xml,text/javascript,text/html");
conn.setRequestProperty("User-Agent", "");
conn.setRequestProperty("Content-Type", ctype);
return conn;
}
解析返回值信息:
private static String getResponseAsString(HttpURLConnection conn) throws IOException {
String charset = getResponseCharset(conn.getContentType());
InputStream es = conn.getErrorStream();
if (es == null) {
return getStreamAsString(conn.getInputStream(), charset);
} else {
String msg = getStreamAsString(es, charset);
if (StringUtils.isEmpty(msg)) {
throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage());
} else {
throw new IOException(msg);
}
}
}
private static String getStreamAsString(InputStream stream, String charset) throws IOException {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset));
StringWriter writer = new StringWriter();
char[] chars = new char[256];
int count = 0;
while ((count = reader.read(chars)) > 0) {
writer.write(chars, 0, count);
}
return writer.toString();
} finally {
if (stream != null) {
stream.close();
}
}
}
private static String getResponseCharset(String ctype) {
String charset = "UTF-8";
if (!StringUtils.isEmpty(ctype)) {
String[] params = ctype.split(";");
for (String param : params) {
param = param.trim();
if (param.startsWith("charset")) {
String[] pair = param.split("=", 2);
if (pair.length == 2) {
if (!StringUtils.isEmpty(pair[1])) {
charset = pair[1].trim();
}
}
break;
}
}
}
return charset;
}
使用方式:
URL url = new URL("http://xxx.com");
HttpURLConnection conn = getConnection(url);
os = conn.getOutputStream();
//POST方式发送参数:param=key¶m=key
//GET方式直接在url后拼接参数即可
os.write(params.getBytes());
String response = getResponseAsString(loginConn);
HttpURLConnection还支持cookie传递:
//在第一个请求结束后,获取cookie信息(一般是在登录操作之后)
String cookie = conn1.getHeaderField("Set-Cookie");
//在第二个请求发送之前,设置cookie
conn2.setRequestProperty("Cookie", cookie);