java Http工具类
package xxx;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
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.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class HttpUtils {
//设置编码格式
String Content-Type= "application/x-www-form-urlencoded; charset=UTF-8";
private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
/**
* get
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doGet(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpGet request = new HttpGet(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
/**
* 向指定 URL 发送GET方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。可为null。
* @return 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
HttpURLConnection conn = null;
StringBuilder result = new StringBuilder();
BufferedReader in = null;
try {
String urlNameString = url;
if (param != null && !param.trim().isEmpty()) {
urlNameString = urlNameString + "?" + param;
}
log.info("发送数据 - {}", urlNameString);
URL realUrl = new URL(urlNameString);
conn = (HttpURLConnection) realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.connect();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
log.info("接收数据 - {}", result);
} catch (Exception e) {
throw new ServiceException("发送GET请求异常", e);
} finally {
closeQuietly(in);
closeQuietly(conn);
}
return result.toString();
}
/**
* post form
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param bodys
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
Map<String, String> bodys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (bodys != null) {
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (String key : bodys.keySet()) {
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
request.setEntity(formEntity);
}
return httpClient.execute(request);
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。可为null。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
HttpURLConnection conn = null;
PrintWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try {
String urlNameString = url;
log.info("发送Post数据 - {}, param:{}", urlNameString, param);
URL realUrl = new URL(urlNameString);
conn = (HttpURLConnection) realUrl.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
//写入请求参数
if (param != null && !param.trim().isEmpty()) {
out.write(param);
out.flush();
}
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
log.info("接收post数据 - {}", result);
} catch (Exception e) {
throw new ServiceException("发送POST请求异常", e);
} finally {
closeQuietly(out);
closeQuietly(in);
closeQuietly(conn);
}
return result.toString();
}
/**
* Post String
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
/**
* Post stream
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
/**
* Put String
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
/**
* Put stream
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
/**
* 发送 PUT请求
* @param url
* @param param
* @return
*/
public static String sendPut(String url, String param) {
HttpURLConnection conn = null;
PrintWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try {
String urlNameString = url;
log.info("sendPut - {}, param:{}", urlNameString, param);
URL realUrl = new URL(urlNameString);
conn = (HttpURLConnection) realUrl.openConnection();
conn.setRequestMethod("PUT");
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
//写入请求参数
if (param != null && !param.trim().isEmpty()) {
out.write(param);
out.flush();
}
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
log.info("recv - {}", result);
} catch (Exception e) {
throw new ServiceException("发送PUT请求异常", e);
} finally {
closeQuietly(out);
closeQuietly(in);
closeQuietly(conn);
}
return result.toString();
}
/**
* Delete
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doDelete(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
StringBuilder sbUrl = new StringBuilder();
sbUrl.append(host);
if (!StringUtils.isBlank(path)) {
sbUrl.append(path);
}
if (null != querys) {
StringBuilder sbQuery = new StringBuilder();
for (Map.Entry<String, String> query : querys.entrySet()) {
if (0 < sbQuery.length()) {
sbQuery.append("&");
}
if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
sbQuery.append(query.getValue());
}
if (!StringUtils.isBlank(query.getKey())) {
sbQuery.append(query.getKey());
if (!StringUtils.isBlank(query.getValue())) {
sbQuery.append("=");
sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
}
}
}
if (0 < sbQuery.length()) {
sbUrl.append("?").append(sbQuery);
}
}
return sbUrl.toString();
}
private static HttpClient wrapClient(String host) {
HttpClient httpClient = new DefaultHttpClient();
if (host.startsWith("https://")) {
sslClient(httpClient);
}
return httpClient;
}
public static String sendFilePost(String url, Map<String, String> params,
List<FileAttach> files) throws Exception {
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--", LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
StringBuilder result = new StringBuilder();
HttpURLConnection conn = null;
DataOutputStream outStream = null;
BufferedReader inStream = null;
try {
log.info("sendPost - {}", url);
URL uri = new URL(url);
conn = (HttpURLConnection) uri.openConnection();
// 缓存的最长时间
conn.setReadTimeout(6 * 1000);
// 允许输入
conn.setDoInput(true);
// 允许输出
conn.setDoOutput(true);
// 不允许使用缓存
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", CHARSET);
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
// 首先组拼文本类型的参数
StringBuilder normalParams = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
normalParams.append(PREFIX);
normalParams.append(BOUNDARY);
normalParams.append(LINEND);
normalParams.append("Content-Disposition: form-data; name=\""
+ entry.getKey() + "\"" + LINEND);
normalParams.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
normalParams.append("Content-Transfer-Encoding: 8bit" + LINEND);
normalParams.append(LINEND);
normalParams.append(entry.getValue());
normalParams.append(LINEND);
}
outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(normalParams.toString().getBytes());
// 发送文件数据
if (files != null && !files.isEmpty()) {
for (FileAttach fileAttach : files) {
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
String contDis = String.format("Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"%s",
fileAttach.getFieldName(), fileAttach.getFileName(), LINEND);
sb1.append(contDis);
sb1.append("Content-Type:" + "application/octet-stream;").append(CHARSET).append(LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes());
outStream.write(fileAttach.getFileBytes());
outStream.write(LINEND.getBytes());
}
}
// 请求结束标志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
//读取响应信息
inStream = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
String line;
while ((line = inStream.readLine()) != null) {
result.append(line);
}
log.info("recv - {}", result);
} catch (Exception e) {
throw new ServiceException("发送带有文件的POST请求异常", e);
} finally {
closeQuietly(outStream);
closeQuietly(inStream);
closeQuietly(conn);
}
return result.toString();
}
private static void sslClient(HttpClient httpClient) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] xcs, String str) {
}
public void checkServerTrusted(X509Certificate[] xcs, String str) {
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = httpClient.getConnectionManager();
SchemeRegistry registry = ccm.getSchemeRegistry();
registry.register(new Scheme("https", ssf, 443));
} catch (KeyManagementException ex) {
throw new RuntimeException(ex);
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
}
}
文件类:
/**
* 文件附件信息
*/
public static class FileAttach {
/**
* form表单字段名称
*/
private String fieldName;
/**
* 文件名称
*/
private String fileName;
/**
* 文件字节
*/
private byte[] fileBytes;
/** 构造函数
* @param fieldName form表单字段名称
* @param fileName 文件名称
* @param fileBytes 文件字节
*/
public FileAttach(String fieldName, String fileName, byte[] fileBytes) {
this.fieldName = fieldName;
this.fileName = fileName;
this.fileBytes = fileBytes;
}
public FileAttach() {
}
private static void closeQuietly(Closeable clo) {
try {
if (clo != null) {
clo.close();
}
} catch (Exception e) {
log.error("资源关闭异常", e);
}
}
/**
* 安静的关闭http连接。如果关闭失败,仅仅打印日志,不抛出异常。
*
*/
private static void closeQuietly(HttpURLConnection conn) {
try {
if (conn != null) {
conn.disconnect();
}
} catch (Exception e) {
log.error("HttpURLConnection关闭异常", e);
}
}
@SuppressWarnings("deprecation")
public static String sendSSLPost(String url, String param) {
StringBuilder result = new StringBuilder();
String urlNameString = url + "?" + param;
HttpsURLConnection conn = null;
DataInputStream indata = null;
try {
log.info("sendSSLPost - {}", urlNameString);
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
URL console = new URL(urlNameString);
conn = (HttpsURLConnection) console.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.connect();
indata = new DataInputStream(conn.getInputStream());
String ret = "";
while (ret != null) {
ret = indata.readLine();
if (ret != null && !ret.trim().equals("")) {
result.append(new String(ret.getBytes("ISO-8859-1"), "utf-8"));
}
}
log.info("recv - {}", result);
} catch (Exception e) {
throw new ServiceException("发送SSL-POST请求异常", e);
} finally {
closeQuietly(indata);
closeQuietly(conn);
}
return result.toString();
}
private static class TrustAnyTrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
}
private static class TrustAnyHostnameVerifier implements HostnameVerifier {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}