package com.md.demo.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
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.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
/**
* 封装了一些采用HttpClient发送HTTP请求的方法
* @see 本工具所采用的是最新的HttpComponents-Client-4.2.1
*/
public class HttpClientUtil {
private static final Logger log = Logger.getLogger(HttpClientUtil.class);
private HttpClientUtil(){}
/**
* 发送HTTP_GET请求
* @see 该方法会自动关闭连接,释放资源
* @param requestURL 请求地址(含参数)
* @param decodeCharset 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
* @return 远程主机响应正文
*/
public static String sendGetRequest(String reqURL, String decodeCharset){
long responseLength = 0; //响应长度
String responseContent = null; //响应内容
HttpClient httpClient = new DefaultHttpClient(); //创建默认的httpClient实例
HttpGet httpGet = new HttpGet(reqURL); //创建org.apache.http.client.methods.HttpGet
try{
HttpResponse response = httpClient.execute(httpGet); //执行GET请求
HttpEntity entity = response.getEntity(); //获取响应实体
if(null != entity){
responseLength = entity.getContentLength();
responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset);
EntityUtils.consume(entity); //Consume response content
}
System.out.println("请求地址: " + httpGet.getURI());
System.out.println("响应状态: " + response.getStatusLine());
System.out.println("响应长度: " + responseLength);
System.out.println("响应内容: " + responseContent);
}catch(ClientProtocolException e){
log.error("该异常通常是协议错误导致,比如构造HttpGet对象时传入的协议不对(将'http'写成'htp')或者服务器端返回的内容不符合HTTP协议要求等,堆栈信息如下", e);
}catch(ParseException e){
log.error(e.getMessage(), e);
}catch(IOException e){
log.error("该异常通常是网络原因引起的,如HTTP服务器未启动等,堆栈信息如下", e);
}finally{
httpClient.getConnectionManager().shutdown(); //关闭连接,释放资源
}
return responseContent;
}
/**
* 发送HTTP_POST请求
* @see 该方法为<code>sendPostRequest(String,String,boolean,String,String)</code>的简化方法
* @see 该方法在对请求数据的编码和响应数据的解码时,所采用的字符集均为UTF-8
* @see 当<code>isEncoder=true</code>时,其会自动对<code>sendData</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,"UTF-8")</code>
* @param isEncoder 用于指明请求数据是否需要UTF-8编码,true为需要
*/
public static String sendPostRequest(String reqURL, String sendData, boolean isEncoder){
return sendPostRequest(reqURL, sendData, isEncoder, null, null);
}
/**
* 发送HTTP_POST请求
* @see 该方法会自动关闭连接,释放资源
* @see 当<code>isEncoder=true</code>时,其会自动对<code>sendData</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,encodeCharset)</code>
* @param reqURL 请求地址
* @param sendData 请求参数,若有多个参数则应拼接成param11=value11¶m22=value22¶m33=value33的形式后,传入该参数中
* @param isEncoder 请求数据是否需要encodeCharset编码,true为需要
* @param encodeCharset 编码字符集,编码请求数据时用之,其为null时默认采用UTF-8解码
* @param decodeCharset 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
* @return 远程主机响应正文
*/
public static String sendPostRequest(String reqURL, String sendData, boolean isEncoder, String encodeCharset, String decodeCharset){
String responseContent = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(reqURL);
//httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=UTF-8");
httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
try{
if(isEncoder){
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
for(String str : sendData.split("&")){
formParams.add(new BasicNameValuePair(str.substring(0,str.indexOf("=")), str.substring(str.indexOf("=")+1)));
}
httpPost.setEntity(new StringEntity(URLEncodedUtils.format(formParams, encodeCharset==null ? "UTF-8" : encodeCharset)));
}else{
httpPost.setEntity(new StringEntity(sendData));
}
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (null != entity) {
responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset);
EntityUtils.consume(entity);
}
}catch(Exception e){
log.error("与[" + reqURL + "]通信过程中发生异常,堆栈信息如下", e);
}finally{
httpClient.getConnectionManager().shutdown();
}
return responseContent;
}
/**
* 发送HTTP_POST请求
* @see 该方法会自动关闭连接,释放资源
* @see 该方法会自动对<code>params</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,encodeCharset)</code>
* @param reqURL 请求地址
* @param params 请求参数
* @param encodeCharset 编码字符集,编码请求数据时用之,其为null时默认采用UTF-8解码
* @param decodeCharset 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
* @return 远程主机响应正文
*/
public static String sendPostRequest(String reqURL, Map<String, String> params, String encodeCharset, String decodeCharset){
String responseContent = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(reqURL);
List<NameValuePair> formParams = new ArrayList<NameValuePair>(); //创建参数队列
for(Map.Entry<String,String> entry : params.entrySet()){
formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
try{
httpPost.setEntity(new UrlEncodedFormEntity(formParams, encodeCharset==null ? "UTF-8" : encodeCharset));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (null != entity) {
responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset);
EntityUtils.consume(entity);
}
}catch(Exception e){
log.error("与[" + reqURL + "]通信过程中发生异常,堆栈信息如下", e);
}finally{
httpClient.getConnectionManager().shutdown();
}
return responseContent;
}
/**
* 发送HTTPS_POST请求
* @see 该方法为<code>sendPostSSLRequest(String,Map<String,String>,String,String)</code>方法的简化方法
* @see 该方法在对请求数据的编码和响应数据的解码时,所采用的字符集均为UTF-8
* @see 该方法会自动对<code>params</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,"UTF-8")</code>
*/
public static String sendPostSSLRequest(String reqURL, Map<String, String> params){
return sendPostSSLRequest(reqURL, params, null, null);
}
/**
* 发送HTTPS_POST请求
* @see 该方法会自动关闭连接,释放资源
* @see 该方法会自动对<code>params</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,encodeCharset)</code>
* @param reqURL 请求地址
* @param params 请求参数
* @param encodeCharset 编码字符集,编码请求数据时用之,其为null时默认采用UTF-8解码
* @param decodeCharset 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
* @return 远程主机响应正文
*/
public static String sendPostSSLRequest(String reqURL, Map<String, String> params, String encodeCharset, String decodeCharset){
String responseContent = "";
HttpClient httpClient = new DefaultHttpClient();
X509TrustManager xtm = new X509TrustManager(){
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
public X509Certificate[] getAcceptedIssuers() {return null;}
};
try {
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[]{xtm}, null);
SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));
HttpPost httpPost = new HttpPost(reqURL);
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
for(Map.Entry<String,String> entry : params.entrySet()){
formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpPost.setEntity(new UrlEncodedFormEntity(formParams, encodeCharset==null ? "UTF-8" : encodeCharset));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (null != entity) {
responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset);
EntityUtils.consume(entity);
}
} catch (Exception e) {
log.error("与[" + reqURL + "]通信过程中发生异常,堆栈信息为", e);
} finally {
httpClient.getConnectionManager().shutdown();
}
return responseContent;
}
/**
* 发送HTTP_POST请求
* @see 若发送的<code>params</code>中含有中文,记得按照双方约定的字符集将中文<code>URLEncoder.encode(string,encodeCharset)</code>
* @see 本方法默认的连接超时时间为30秒,默认的读取超时时间为30秒
* @param reqURL 请求地址
* @param params 发送到远程主机的正文数据,其数据类型为<code>java.util.Map<String, String></code>
* @return 远程主机响应正文`HTTP状态码,如<code>"SUCCESS`200"</code><br>若通信过程中发生异常则返回"Failed`HTTP状态码",如<code>"Failed`500"</code>
*/
public static String sendPostRequestByJava(String reqURL, Map<String, String> params){
StringBuilder sendData = new StringBuilder();
for(Map.Entry<String, String> entry : params.entrySet()){
sendData.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
if(sendData.length() > 0){
sendData.setLength(sendData.length() - 1); //删除最后一个&符号
}
return sendPostRequestByJava(reqURL, sendData.toString());
}
/**
* 发送HTTP_POST请求
* @see 若发送的<code>sendData</code>中含有中文,记得按照双方约定的字符集将中文<code>URLEncoder.encode(string,encodeCharset)</code>
* @see 本方法默认的连接超时时间为30秒,默认的读取超时时间为30秒
* @param reqURL 请求地址
* @param sendData 发送到远程主机的正文数据
* @return 远程主机响应正文`HTTP状态码,如<code>"SUCCESS`200"</code><br>若通信过程中发生异常则返回"Failed`HTTP状态码",如<code>"Failed`500"</code>
*/
public static String sendPostRequestByJava(String reqURL, String sendData){
HttpURLConnection httpURLConnection = null;
OutputStream out = null; //写
InputStream in = null; //读
int httpStatusCode = 0; //远程主机响应的HTTP状态码
try{
URL sendUrl = new URL(reqURL);
httpURLConnection = (HttpURLConnection)sendUrl.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true); //指示应用程序要将数据写入URL连接,其值默认为false
httpURLConnection.setUseCaches(false);
httpURLConnection.setConnectTimeout(30000); //30秒连接超时
httpURLConnection.setReadTimeout(30000); //30秒读取超时
out = httpURLConnection.getOutputStream();
out.write(sendData.toString().getBytes());
//清空缓冲区,发送数据
out.flush();
//获取HTTP状态码
httpStatusCode = httpURLConnection.getResponseCode();
//该方法只能获取到[HTTP/1.0 200 OK]中的[OK]
//若对方响应的正文放在了返回报文的最后一行,则该方法获取不到正文,而只能获取到[OK],稍显遗憾
//respData = httpURLConnection.getResponseMessage();
// //处理返回结果
// BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
// String row = null;
// String respData = "";
// if((row=br.readLine()) != null){ //readLine()方法在读到换行[\n]或回车[\r]时,即认为该行已终止
// respData = row; //HTTP协议POST方式的最后一行数据为正文数据
// }
// br.close();
in = httpURLConnection.getInputStream();
byte[] byteDatas = new byte[in.available()];
in.read(byteDatas);
return new String(byteDatas) + "`" + httpStatusCode;
}catch(Exception e){
log.error(e.getMessage());
return "Failed`" + httpStatusCode;
}finally{
if(out != null){
try{
out.close();
}catch (Exception e){
log.error("关闭输出流时发生异常,堆栈信息如下", e);
}
}
if(in != null){
try{
in.close();
}catch(Exception e){
log.error("关闭输入流时发生异常,堆栈信息如下", e);
}
}
if(httpURLConnection != null){
httpURLConnection.disconnect();
httpURLConnection = null;
}
}
}
}
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
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.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
/**
* 封装了一些采用HttpClient发送HTTP请求的方法
* @see 本工具所采用的是最新的HttpComponents-Client-4.2.1
*/
public class HttpClientUtil {
private static final Logger log = Logger.getLogger(HttpClientUtil.class);
private HttpClientUtil(){}
/**
* 发送HTTP_GET请求
* @see 该方法会自动关闭连接,释放资源
* @param requestURL 请求地址(含参数)
* @param decodeCharset 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
* @return 远程主机响应正文
*/
public static String sendGetRequest(String reqURL, String decodeCharset){
long responseLength = 0; //响应长度
String responseContent = null; //响应内容
HttpClient httpClient = new DefaultHttpClient(); //创建默认的httpClient实例
HttpGet httpGet = new HttpGet(reqURL); //创建org.apache.http.client.methods.HttpGet
try{
HttpResponse response = httpClient.execute(httpGet); //执行GET请求
HttpEntity entity = response.getEntity(); //获取响应实体
if(null != entity){
responseLength = entity.getContentLength();
responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset);
EntityUtils.consume(entity); //Consume response content
}
System.out.println("请求地址: " + httpGet.getURI());
System.out.println("响应状态: " + response.getStatusLine());
System.out.println("响应长度: " + responseLength);
System.out.println("响应内容: " + responseContent);
}catch(ClientProtocolException e){
log.error("该异常通常是协议错误导致,比如构造HttpGet对象时传入的协议不对(将'http'写成'htp')或者服务器端返回的内容不符合HTTP协议要求等,堆栈信息如下", e);
}catch(ParseException e){
log.error(e.getMessage(), e);
}catch(IOException e){
log.error("该异常通常是网络原因引起的,如HTTP服务器未启动等,堆栈信息如下", e);
}finally{
httpClient.getConnectionManager().shutdown(); //关闭连接,释放资源
}
return responseContent;
}
/**
* 发送HTTP_POST请求
* @see 该方法为<code>sendPostRequest(String,String,boolean,String,String)</code>的简化方法
* @see 该方法在对请求数据的编码和响应数据的解码时,所采用的字符集均为UTF-8
* @see 当<code>isEncoder=true</code>时,其会自动对<code>sendData</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,"UTF-8")</code>
* @param isEncoder 用于指明请求数据是否需要UTF-8编码,true为需要
*/
public static String sendPostRequest(String reqURL, String sendData, boolean isEncoder){
return sendPostRequest(reqURL, sendData, isEncoder, null, null);
}
/**
* 发送HTTP_POST请求
* @see 该方法会自动关闭连接,释放资源
* @see 当<code>isEncoder=true</code>时,其会自动对<code>sendData</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,encodeCharset)</code>
* @param reqURL 请求地址
* @param sendData 请求参数,若有多个参数则应拼接成param11=value11¶m22=value22¶m33=value33的形式后,传入该参数中
* @param isEncoder 请求数据是否需要encodeCharset编码,true为需要
* @param encodeCharset 编码字符集,编码请求数据时用之,其为null时默认采用UTF-8解码
* @param decodeCharset 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
* @return 远程主机响应正文
*/
public static String sendPostRequest(String reqURL, String sendData, boolean isEncoder, String encodeCharset, String decodeCharset){
String responseContent = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(reqURL);
//httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=UTF-8");
httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
try{
if(isEncoder){
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
for(String str : sendData.split("&")){
formParams.add(new BasicNameValuePair(str.substring(0,str.indexOf("=")), str.substring(str.indexOf("=")+1)));
}
httpPost.setEntity(new StringEntity(URLEncodedUtils.format(formParams, encodeCharset==null ? "UTF-8" : encodeCharset)));
}else{
httpPost.setEntity(new StringEntity(sendData));
}
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (null != entity) {
responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset);
EntityUtils.consume(entity);
}
}catch(Exception e){
log.error("与[" + reqURL + "]通信过程中发生异常,堆栈信息如下", e);
}finally{
httpClient.getConnectionManager().shutdown();
}
return responseContent;
}
/**
* 发送HTTP_POST请求
* @see 该方法会自动关闭连接,释放资源
* @see 该方法会自动对<code>params</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,encodeCharset)</code>
* @param reqURL 请求地址
* @param params 请求参数
* @param encodeCharset 编码字符集,编码请求数据时用之,其为null时默认采用UTF-8解码
* @param decodeCharset 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
* @return 远程主机响应正文
*/
public static String sendPostRequest(String reqURL, Map<String, String> params, String encodeCharset, String decodeCharset){
String responseContent = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(reqURL);
List<NameValuePair> formParams = new ArrayList<NameValuePair>(); //创建参数队列
for(Map.Entry<String,String> entry : params.entrySet()){
formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
try{
httpPost.setEntity(new UrlEncodedFormEntity(formParams, encodeCharset==null ? "UTF-8" : encodeCharset));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (null != entity) {
responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset);
EntityUtils.consume(entity);
}
}catch(Exception e){
log.error("与[" + reqURL + "]通信过程中发生异常,堆栈信息如下", e);
}finally{
httpClient.getConnectionManager().shutdown();
}
return responseContent;
}
/**
* 发送HTTPS_POST请求
* @see 该方法为<code>sendPostSSLRequest(String,Map<String,String>,String,String)</code>方法的简化方法
* @see 该方法在对请求数据的编码和响应数据的解码时,所采用的字符集均为UTF-8
* @see 该方法会自动对<code>params</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,"UTF-8")</code>
*/
public static String sendPostSSLRequest(String reqURL, Map<String, String> params){
return sendPostSSLRequest(reqURL, params, null, null);
}
/**
* 发送HTTPS_POST请求
* @see 该方法会自动关闭连接,释放资源
* @see 该方法会自动对<code>params</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,encodeCharset)</code>
* @param reqURL 请求地址
* @param params 请求参数
* @param encodeCharset 编码字符集,编码请求数据时用之,其为null时默认采用UTF-8解码
* @param decodeCharset 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
* @return 远程主机响应正文
*/
public static String sendPostSSLRequest(String reqURL, Map<String, String> params, String encodeCharset, String decodeCharset){
String responseContent = "";
HttpClient httpClient = new DefaultHttpClient();
X509TrustManager xtm = new X509TrustManager(){
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
public X509Certificate[] getAcceptedIssuers() {return null;}
};
try {
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[]{xtm}, null);
SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));
HttpPost httpPost = new HttpPost(reqURL);
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
for(Map.Entry<String,String> entry : params.entrySet()){
formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpPost.setEntity(new UrlEncodedFormEntity(formParams, encodeCharset==null ? "UTF-8" : encodeCharset));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (null != entity) {
responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset);
EntityUtils.consume(entity);
}
} catch (Exception e) {
log.error("与[" + reqURL + "]通信过程中发生异常,堆栈信息为", e);
} finally {
httpClient.getConnectionManager().shutdown();
}
return responseContent;
}
/**
* 发送HTTP_POST请求
* @see 若发送的<code>params</code>中含有中文,记得按照双方约定的字符集将中文<code>URLEncoder.encode(string,encodeCharset)</code>
* @see 本方法默认的连接超时时间为30秒,默认的读取超时时间为30秒
* @param reqURL 请求地址
* @param params 发送到远程主机的正文数据,其数据类型为<code>java.util.Map<String, String></code>
* @return 远程主机响应正文`HTTP状态码,如<code>"SUCCESS`200"</code><br>若通信过程中发生异常则返回"Failed`HTTP状态码",如<code>"Failed`500"</code>
*/
public static String sendPostRequestByJava(String reqURL, Map<String, String> params){
StringBuilder sendData = new StringBuilder();
for(Map.Entry<String, String> entry : params.entrySet()){
sendData.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
if(sendData.length() > 0){
sendData.setLength(sendData.length() - 1); //删除最后一个&符号
}
return sendPostRequestByJava(reqURL, sendData.toString());
}
/**
* 发送HTTP_POST请求
* @see 若发送的<code>sendData</code>中含有中文,记得按照双方约定的字符集将中文<code>URLEncoder.encode(string,encodeCharset)</code>
* @see 本方法默认的连接超时时间为30秒,默认的读取超时时间为30秒
* @param reqURL 请求地址
* @param sendData 发送到远程主机的正文数据
* @return 远程主机响应正文`HTTP状态码,如<code>"SUCCESS`200"</code><br>若通信过程中发生异常则返回"Failed`HTTP状态码",如<code>"Failed`500"</code>
*/
public static String sendPostRequestByJava(String reqURL, String sendData){
HttpURLConnection httpURLConnection = null;
OutputStream out = null; //写
InputStream in = null; //读
int httpStatusCode = 0; //远程主机响应的HTTP状态码
try{
URL sendUrl = new URL(reqURL);
httpURLConnection = (HttpURLConnection)sendUrl.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true); //指示应用程序要将数据写入URL连接,其值默认为false
httpURLConnection.setUseCaches(false);
httpURLConnection.setConnectTimeout(30000); //30秒连接超时
httpURLConnection.setReadTimeout(30000); //30秒读取超时
out = httpURLConnection.getOutputStream();
out.write(sendData.toString().getBytes());
//清空缓冲区,发送数据
out.flush();
//获取HTTP状态码
httpStatusCode = httpURLConnection.getResponseCode();
//该方法只能获取到[HTTP/1.0 200 OK]中的[OK]
//若对方响应的正文放在了返回报文的最后一行,则该方法获取不到正文,而只能获取到[OK],稍显遗憾
//respData = httpURLConnection.getResponseMessage();
// //处理返回结果
// BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
// String row = null;
// String respData = "";
// if((row=br.readLine()) != null){ //readLine()方法在读到换行[\n]或回车[\r]时,即认为该行已终止
// respData = row; //HTTP协议POST方式的最后一行数据为正文数据
// }
// br.close();
in = httpURLConnection.getInputStream();
byte[] byteDatas = new byte[in.available()];
in.read(byteDatas);
return new String(byteDatas) + "`" + httpStatusCode;
}catch(Exception e){
log.error(e.getMessage());
return "Failed`" + httpStatusCode;
}finally{
if(out != null){
try{
out.close();
}catch (Exception e){
log.error("关闭输出流时发生异常,堆栈信息如下", e);
}
}
if(in != null){
try{
in.close();
}catch(Exception e){
log.error("关闭输入流时发生异常,堆栈信息如下", e);
}
}
if(httpURLConnection != null){
httpURLConnection.disconnect();
httpURLConnection = null;
}
}
}
}
相关推荐
HTTPClient工具类,完整,HTTPClient工具类,完整,HTTPClient工具类,完整HTTPClient工具类,完整,HTTPClient工具类,完整
1.高效简单池化的HttpClient工具类,提供单元测试用列。 2.支持基于SpringBoot 2.1.x的自动装载模块,引用依赖即可使用。 3.公司几十个项目都使用该工具类访问第三方的Http/Https+json协议接口。 4.经过上市公司多个...
在本文中,我们将深入探讨HttpClient工具类的创建与使用,以及如何自定义返回的对象。 首先,我们需要引入HttpClient的相关依赖。在Maven项目中,可以在pom.xml文件中添加以下依赖: ```xml <groupId>org.apache...
java httpClient 工具类 java httpClient 工具类 java httpClient 工具类 java httpClient 工具类 java httpClient 工具类 java httpClient 工具类 java httpClient 工具类 java httpClient 工具类 java httpClient ...
httpClient 工具类,简化请求开发,拿来即用,我用在SpringBoot框架;对于依赖,你可以根据包名导入。
7. **EntityUtils**:一个工具类,用于处理响应实体,如读取响应内容。例如: ```java String responseBody = EntityUtils.toString(response.getEntity()); ``` 8. **HttpContext**:提供了请求执行的上下文...
4.5.2--修改版,用注释的形式加入了maven的依赖代码;
总之,这个HttpClient工具类提供了一个简洁易用的接口,帮助开发者快速、方便地进行HTTP请求,无论是在进行API调用还是数据交互,都能大大简化工作流程。通过这个工具类,你无需深入了解HttpClient的底层实现,只需...
在实际项目中,通常会封装一个HttpClient工具类,将上述操作抽象成便捷的方法,方便其他代码调用。文件`httpClientUtil`可能就是这样一个工具类,包含了上述功能的实现。通过阅读和理解这个工具类的代码,我们可以更...
HttpClientHelper 是一个C#编写的工具类,主要目的是简化HTTP客户端操作,提供同步和异步的请求方法,返回数据格式多样,包括字符串、泛型类型和XML。在爬虫开发中,这样的工具类非常实用,因为爬虫经常需要与各种...
《HttpClient工具类包详解》 在Java开发中, HttpClient是一个非常重要的工具库,它提供了强大的HTTP客户端编程接口,使得开发者可以方便地进行HTTP通信。本文将深入探讨HttpClient工具类包,包括其核心组件、功能...
HttpClient工具类中的`doGet`通常会包含以下步骤: 1. 创建HttpClient实例。 2. 构建HttpGet请求对象,指定URL。 3. 设置请求头,如Accept、Content-Type等。 4. 使用HttpClient执行请求并获取HttpResponse对象。 5....
【HttpClient工具类封装】 在Java开发中,Apache HttpClient是一个强大的HTTP客户端库,常用于执行HTTP请求,如GET、POST、PUT和DELETE等。这个工具类是基于HttpClient 4.5.12版本进行封装,目的是简化HTTP操作并...
通过以上步骤,开发者可以使用HTTPClient工具类高效地执行HTTP请求,获取并处理服务器的响应。这个工具类集合的目的是简化这一过程,使得代码更加简洁易懂,同时也提高了开发效率。在实际应用中,可以根据具体需求...