java连接http_关于Java去连接HTTP地址的操作

使用HTTPClient进行操作,可以忽略SSL

/**

* @author Kai

* @Date 2015-7-28 19:47:16

*/

public class HTTPClient {

//HTTP请求读取超时时间

private static final int SOCKET_TIME_OUT = 5000;

//HTTP请求连接时间

private static final int CONNECT_TIME_OUT = 5000;

//请求重试次数

private static final int RETRY_TIMES = 3;

/**

*

* @param address 请求地址

* @param method  请求方式

* @param params 请求参数

* @param paramSendType 发送类型

* @param cookies 设置cookies值发送

* @return

*/

public String request(String address, String method, String params, String paramSendType, String cookies) {

address = address.trim();

CloseableHttpResponse closeableHttpResponse = null;

if (SupportProtocol.HTTP_METHOD_GET.equalsIgnoreCase(method)) {

closeableHttpResponse = this.GET(address, params, paramSendType, cookies);

} else if (SupportProtocol.HTTP_METHOD_POST.equalsIgnoreCase(method)) {

closeableHttpResponse = this.POST(address, params, paramSendType, cookies);

} else if (SupportProtocol.HTTP_METHOD_PUT.equalsIgnoreCase(method)) {

closeableHttpResponse = this.PUT(address, params, paramSendType, cookies);

} else {

closeableHttpResponse = this.POST(address, params, paramSendType, cookies);

}

return this.buildReponseMsg(closeableHttpResponse);

}

private CloseableHttpResponse PUT(String address, String params, String paramSendType, String cookies) {

try {

URI uri = URI.create(address);

HttpPut httpPut = new HttpPut(uri);

RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIME_OUT).setConnectTimeout(CONNECT_TIME_OUT).build();

httpPut.setConfig(requestConfig);

if (SupportProtocol.SUPPORT_JSON.equalsIgnoreCase(paramSendType)) {

httpPut.setHeader("Content-Type", "application/json; charset=UTF-8");

StringEntity entity = new StringEntity(params, ContentType.APPLICATION_JSON);

httpPut.setEntity(entity);

} else if (SupportProtocol.SUPPORT_JSON.equalsIgnoreCase(paramSendType)) {

httpPut.setHeader("Content-Type", "application/xml; charset=UTF-8");

StringEntity entity = new StringEntity(params, ContentType.APPLICATION_XML);

httpPut.setEntity(entity);

} else {

httpPut.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

StringEntity entity = new StringEntity(params, ContentType.APPLICATION_FORM_URLENCODED);

httpPut.setEntity(entity);

}

if (StrUtil.isNotEmpty(cookies)) {

httpPut.setHeader("Cookie", cookies);

}

CloseableHttpClient httpClient = HttpClients.createDefault();

if (address.toLowerCase().startsWith("https")) {

httpClient = this.createSSLClientDefault();

}

return httpClient.execute(httpPut);

} catch (Exception ex) {

LogUtil.error(ex);

}

return null;

}

private CloseableHttpResponse GET(String address, String params, String paramSendType, String cookies) {

try {

URI uri;

if (EmptyUtil.isNotEmpty(params)) {

uri = URI.create(String.format("%s?%s", address, params));

} else {

uri = URI.create(address);

}

HttpGet httpGet = new HttpGet(uri);

RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIME_OUT).setConnectTimeout(CONNECT_TIME_OUT).build();

httpGet.setConfig(requestConfig);

if (SupportProtocol.SUPPORT_JSON.equalsIgnoreCase(paramSendType)) {

httpGet.setHeader("Content-Type", "application/json; charset=UTF-8");

} else if (SupportProtocol.SUPPORT_XML.equalsIgnoreCase(paramSendType)) {

httpGet.setHeader("Content-Type", "application/xml; charset=UTF-8");

} else {

httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

}

if (StrUtil.isNotEmpty(cookies)) {

httpGet.setHeader("Cookie", cookies);

}

CloseableHttpClient httpClient = HttpClients.createDefault();

if (address.toLowerCase().startsWith("https")) {

httpClient = this.createSSLClientDefault();

}

return httpClient.execute(httpGet);

} catch (Exception ex) {

LogUtil.error(ex);

}

return null;

}

private CloseableHttpResponse POST(String address, String params, String paramSendType, String cookies) {

try {

URI uri = URI.create(address);

HttpPost httpPost = new HttpPost(uri);

RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIME_OUT).setConnectTimeout(CONNECT_TIME_OUT).build();

httpPost.setConfig(requestConfig);

if (SupportProtocol.SUPPORT_JSON.equalsIgnoreCase(paramSendType)) {

httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");

StringEntity entity = new StringEntity(params, ContentType.APPLICATION_JSON);

httpPost.setEntity(entity);

} else if (SupportProtocol.SUPPORT_XML.equalsIgnoreCase(paramSendType)) {

httpPost.setHeader("Content-Type", "application/xml; charset=UTF-8");

StringEntity entity = new StringEntity(params, ContentType.APPLICATION_XML);

httpPost.setEntity(entity);

} else {

httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

StringEntity entity = new StringEntity(params, ContentType.APPLICATION_FORM_URLENCODED);

httpPost.setEntity(entity);

}

if (StrUtil.isNotEmpty(cookies)) {

httpPost.setHeader("Cookie", cookies);

}

CloseableHttpClient httpClient = HttpClients.createDefault();

if (address.toLowerCase().startsWith("https")) {

httpClient = this.createSSLClientDefault();

}

return httpClient.execute(httpPost);

} catch (Exception ex) {

LogUtil.error(ex);

}

return null;

}

private CloseableHttpClient createSSLClientDefault() {

try {

SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

@Override

public boolean isTrusted(X509Certificate[] chain,

String authType) throws CertificateException {

return true;

}

}).build();

SSLSocketFactory ssf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

return HttpClients.custom().setSSLSocketFactory(ssf).build();

} catch (Exception e) {

LogUtil.error(e.getMessage());

}

return HttpClients.createDefault();

}

private String buildReponseMsg(CloseableHttpResponse closeableHttpResponse) {

if (closeableHttpResponse == null) {

return null;

}

try {

int code = closeableHttpResponse.getStatusLine().getStatusCode();

String msg = EntityUtils.toString(closeableHttpResponse.getEntity());

if (code == HttpStatus.SC_OK) {

return msg;

}

} catch (Exception ex) {

LogUtil.error(ex);

}

return null;

}

}

使用URLConnection读取数据,访问HTTPS貌似有问题

package com.k.ctc.http;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.io.UnsupportedEncodingException;

import java.net.URL;

import java.net.URLConnection;

import java.net.URLEncoder;

import java.util.Map;

/**

*

* @author Kai

*/

public class Connector {

public String GET(String address, Map params) throws Exception {

String param = this.buildParams(params);

URL url = new URL(address + "?" + param);

URLConnection conn = url.openConnection();

return this.readData(conn);

}

public String GET(String address, String params) throws Exception {

URL url = new URL(address + "?" + params);

URLConnection conn = url.openConnection();

return this.readData(conn);

}

public String POST(String address, Map params) throws Exception {

String param = this.buildParams(params);

URL url = new URL(address);

URLConnection conn = url.openConnection();

this.postData(conn, param);

return this.readData(conn);

}

public String POST(String address, String param) throws Exception {

URL url = new URL(address);

URLConnection conn = url.openConnection();

this.postData(conn, param);

return this.readData(conn);

}

private String buildParams(Map params) throws UnsupportedEncodingException {

StringBuilder sb = new StringBuilder();

for (Map.Entry param : params.entrySet()) {

sb.append(param.getKey()).append("=");

sb.append(URLEncoder.encode(param.getValue(), "UTF-8"));

sb.append("&");

}

return sb.toString();

}

private void postData(final URLConnection conn, String requestData) throws Exception {

conn.setDoOutput(true);

OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

wr.write(requestData);

wr.flush();

wr.close();

}

private String readData(final URLConnection conn) throws Exception {

String responseData = "";

BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

String line;

while ((line = rd.readLine()) != null) {

responseData += line;

}

responseData = new String(responseData.getBytes(), "UTF-8");

rd.close();

return responseData;

}

}

做个代码记录 Maven引用

org.apache.httpcomponents

httpclient

4.4

org.apache.httpcomponents

httpcore

4.4

org.apache.httpcomponents

httpcore-nio

4.4

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值