?
https://blog.csdn.net/lchq1995/article/details/88293047
? ? ? // 設(shè)置請求參數(shù)
Map<String, String> param = new HashMap<String, String>();
param.put("test", "test");
// 設(shè)置請求頭信息
Map<String, String> headMap =new HashMap<String, String>();
headMap.put("Authorization", token);
? ? ? ? headMap.put("Content-type", "application/json");
? ? ? ? // 判斷token獲取的user信息
? ? String tkJson = HttpClientUtils.connectPost(ssoGetUserURL, headMap, param);
? ? ? ? JSONObject resultJson = JSONObject.fromObject(tkJson);
? ? ? ? String employeeNo=json.getString("EmployeeNo");
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URIBuilder;
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.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.ByteArrayBuffer;
import org.apache.http.util.EntityUtils;
/**
* 封裝了一些采用HttpClient發(fā)送HTTP請求的方法
*
* @see 本工具所采用的是最新的HttpComponents-Client-4.2.1
*/
public class HttpClientUtils {
private static Log logger = LogFactory.getLog(HttpClientUtils.class);
/**
* 設(shè)置請求頭和參數(shù) post提交
*
* @param urlStr
*? ? ? ? ? ? 地址
* @param headMap
*? ? ? ? ? ? 請求頭
* @param paramMap
*? ? ? ? ? ? 內(nèi)容參數(shù)
* @return
*/
public static String connectPost(String urlStr, Map<String, String> headMap, Map<String, String> paramMap) {
logger.info("========設(shè)置請求頭和參數(shù)并以 post提交=======");
URL url;
String sCurrentLine = "";
String sTotalString = "";
DataOutputStream out = null;
try {
url = new URL(urlStr);
logger.info("請求地址:" + urlStr);
URLConnection URLconnection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) URLconnection;
// httpConnection.setRequestProperty("Content-type", "application/json");
httpConnection.setRequestProperty("Accept-Charset", "utf-8");
httpConnection.setRequestProperty("contentType", "utf-8");
if (headMap != null && !headMap.isEmpty()) {
for (String key : headMap.keySet()) {
logger.info("頭部信息key:" + key + "===值: " + headMap.get(key));
httpConnection.setRequestProperty(key, headMap.get(key));
}
}
httpConnection.setRequestMethod("POST");
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
StringBuffer params = new StringBuffer();
// 表單參數(shù)與get形式一樣
if (paramMap != null && !paramMap.isEmpty()) {
for (String key : paramMap.keySet()) {
if (params.length() > 1) {
params.append("&");
}
params.append(key).append("=").append(paramMap.get(key).trim());
}
logger.info("請求參數(shù): " + params.toString());
}
//System.out.println("params = " + params.toString());
out = new DataOutputStream(httpConnection.getOutputStream());
// 發(fā)送請求參數(shù)
if (params!=null) {
out.writeBytes(params.toString());
}
// flush輸出流的緩沖
out.flush();
// int responseCode = httpConnection.getResponseCode();
// if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream urlStream = httpConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlStream));
while ((sCurrentLine = bufferedReader.readLine()) != null) {
sTotalString += sCurrentLine;
}
// //System.out.println(sTotalString);
// 假設(shè)該url頁面輸出為"OK"
// }else{
// System.err.println("FIAL");
// }
} catch (Exception e) {
logger.info("請求錯誤: " + e.getMessage());
logger.error("系統(tǒng)錯誤:",e);
} finally {
}
logger.info("響應(yīng)信息: " + sTotalString);
return sTotalString;
}
public static void test() throws Exception{
? ? ? ? String url = "http://******/api/hdfs/proxy/create?username=******&password=*****&uri=/test/test-xx.txt";
? ? ? ? byte[] bytes = "1".getBytes();
? ? ? ? HttpClient client = HttpClients.createDefault();
? ? ? ? RequestBuilder requestBuilder = RequestBuilder.post();
? ? ? ? requestBuilder.setEntity(new ByteArrayEntity(bytes));
? ? ? ? requestBuilder.setUri(url);
? ? ? ? HttpResponse response = client.execute(requestBuilder.build());
? ? ? ? HttpEntity entity = response.getEntity();
? ? ? ? //獲得響應(yīng)流
? ? ? ? InputStream is = entity.getContent();
? ? ? ? //讀取流中內(nèi)容
? ? ? ? ByteArrayBuffer buffer = new ByteArrayBuffer(4096);
? ? ? ? byte[] tmp = new byte[4096];
? ? ? ? int count;
? ? ? ? try {
? ? ? ? ? ? while ((count = is.read(tmp)) != -1) {
? ? ? ? ? ? ? ? buffer.append(tmp, 0, count);
? ? ? ? ? ? }
? ? ? ? } catch (EOFException e) {
? ? ? ? ? ? logger.error("系統(tǒng)錯誤:",e);
? ? ? ? }
? ? ? ? //System.out.println(new String(buffer.toByteArray()));
? ? }
/**
* Http Get方法
*
* @param url
* @param param
* @return
*/
public static String doGet(String url, Map<String, String> param) {
// 創(chuàng)建Httpclient對象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 創(chuàng)建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 創(chuàng)建http GET請求
HttpGet httpGet = new HttpGet(uri);
// 執(zhí)行請求
response = httpclient.execute(httpGet);
// 判斷返回狀態(tài)是否為200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
logger.error("系統(tǒng)錯誤:",e);
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
logger.error("系統(tǒng)錯誤:",e);
}
}
return resultString;
}
/**
* Http Get方法
*
* @param url
* @param param
* @return
*/
public static String doGet(String url,Map<String, String> headMap,Map<String, String> param) {
// 創(chuàng)建Httpclient對象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 創(chuàng)建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 創(chuàng)建http GET請求
HttpGet httpGet = new HttpGet(uri);
if (headMap != null && !headMap.isEmpty()) {
for (String key : headMap.keySet()) {
logger.info("頭部信息key:" + key + "===值: " + headMap.get(key));
httpGet.addHeader(key, headMap.get(key));
}
}
// 執(zhí)行請求
response = httpclient.execute(httpGet);
// 判斷返回狀態(tài)是否為200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
logger.error("系統(tǒng)錯誤:",e);
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
logger.error("系統(tǒng)錯誤:",e);
}
}
return resultString;
}
public static String doGet(String url) {
return doGet(url, null);
}
/**
* httpclient post方法
*
* @param url
* @param param
* @return
*/
public static String doPost(String url,Map<String, String> headers,Map<String, String> param) {
// 創(chuàng)建Httpclient對象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 創(chuàng)建Http Post請求
HttpPost httpPost = new HttpPost(url);
if(headers != null) {
for (String key : headers.keySet()) {
httpPost.setHeader(key, headers.get(key));
}
}
// 創(chuàng)建參數(shù)列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模擬表單
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
httpPost.setEntity(entity);
}
// 執(zhí)行http請求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
logger.error("系統(tǒng)錯誤:",e);
} finally {
try {
if (response!=null) {
response.close();
}
} catch (IOException e) {
logger.error("系統(tǒng)錯誤:",e);
}
}
return resultString;
}
public static String doPost(String url) {
return doPost(url,null,null);
}
/**
* 請求的參數(shù)類型為json
*
* @param url
* @param json
* @return {username:"",pass:""}
*/
public static String doPostJson(String url, String json) {
logger.info("=====請求地址:"+url);
// 創(chuàng)建Httpclient對象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 創(chuàng)建Http Post請求
HttpPost httpPost = new HttpPost(url);
// 創(chuàng)建請求內(nèi)容
logger.info("=====請求參數(shù):"+json);
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 執(zhí)行http請求
response = httpClient.execute(httpPost);
logger.info("=====響應(yīng)參數(shù):"+response);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
logger.error("系統(tǒng)錯誤:",e);
} finally {
try {
if (response!=null) {
response.close();
}
} catch (IOException e) {
logger.error("系統(tǒng)錯誤:",e);
}
}
return resultString;
}
/**
* 發(fā)送HTTP_GET請求
*
* @see 該方法會自動關(guān)閉連接,釋放資源
* @param requestURL
*? ? ? ? ? ? 請求地址(含參數(shù))
* @param decodeCharset
*? ? ? ? ? ? 解碼字符集,解析響應(yīng)數(shù)據(jù)時用之,其為null時默認采用UTF-8解碼
* @return 遠程主機響應(yīng)正文
*/
public static String sendGetRequest(String reqURL, String decodeCharset) {
long responseLength = 0; // 響應(yīng)長度
String responseContent = null; // 響應(yīng)內(nèi)容
HttpClient httpClient = new DefaultHttpClient(); // 創(chuàng)建默認的httpClient實例
HttpGet httpGet = new HttpGet(reqURL); // 創(chuàng)建org.apache.http.client.methods.HttpGet
try {
HttpResponse response = httpClient.execute(httpGet); // 執(zhí)行GET請求
HttpEntity entity = response.getEntity(); // 獲取響應(yīng)實體
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("響應(yīng)狀態(tài): " + response.getStatusLine());
//System.out.println("響應(yīng)長度: " + responseLength);
//System.out.println("響應(yīng)內(nèi)容: " + responseContent);
} catch (ClientProtocolException e) {
logger.debug("該異常通常是協(xié)議錯誤導(dǎo)致,比如構(gòu)造HttpGet對象時傳入的協(xié)議不對(將'http'寫成'htp')或者服務(wù)器端返回的內(nèi)容不符合HTTP協(xié)議要求等,堆棧信息如下", e);
} catch (ParseException e) {
logger.debug(e.getMessage(), e);
} catch (IOException e) {
logger.debug("該異常通常是網(wǎng)絡(luò)原因引起的,如HTTP服務(wù)器未啟動等,堆棧信息如下", e);
} finally {
httpClient.getConnectionManager().shutdown(); // 關(guān)閉連接,釋放資源
}
return responseContent;
}
/**
* 發(fā)送HTTP_POST請求
*
* @see 該方法為<code>sendPostRequest(String,String,boolean,String,String)</code>的簡化方法
* @see 該方法在對請求數(shù)據(jù)的編碼和響應(yīng)數(shù)據(jù)的解碼時,所采用的字符集均為UTF-8
* @see 當(dāng)<code>isEncoder=true</code>時,其會自動對<code>sendData</code>中的[中文][|][
*? ? ? ]等特殊字符進行<code>URLEncoder.encode(string,"UTF-8")</code>
* @param isEncoder
*? ? ? ? ? ? 用于指明請求數(shù)據(jù)是否需要UTF-8編碼,true為需要
*/
public static String sendPostRequest(String reqURL, String sendData, boolean isEncoder) {
return sendPostRequest(reqURL, sendData, isEncoder, null, null);
}
/**
* 發(fā)送HTTP_POST請求
*
* @see 該方法會自動關(guān)閉連接,釋放資源
* @see 當(dāng)<code>isEncoder=true</code>時,其會自動對<code>sendData</code>中的[中文][|][
*? ? ? ]等特殊字符進行<code>URLEncoder.encode(string,encodeCharset)</code>
* @param reqURL
*? ? ? ? ? ? 請求地址
* @param sendData
*? ? ? ? ? ? 請求參數(shù),若有多個參數(shù)則應(yīng)拼接成param11=value11&22=value22&33=value33的形式后,傳入該參數(shù)中
* @param isEncoder
*? ? ? ? ? ? 請求數(shù)據(jù)是否需要encodeCharset編碼,true為需要
* @param encodeCharset
*? ? ? ? ? ? 編碼字符集,編碼請求數(shù)據(jù)時用之,其為null時默認采用UTF-8解碼
* @param decodeCharset
*? ? ? ? ? ? 解碼字符集,解析響應(yīng)數(shù)據(jù)時用之,其為null時默認采用UTF-8解碼
* @return 遠程主機響應(yīng)正文
*/
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) {
logger.debug("與[" + reqURL + "]通信過程中發(fā)生異常,堆棧信息如下", e);
} finally {
httpClient.getConnectionManager().shutdown();
}
return responseContent;
}
/**
* 發(fā)送HTTP_POST請求
*
* @see 該方法會自動關(guān)閉連接,釋放資源
* @see 該方法會自動對<code>params</code>中的[中文][|][
*? ? ? ]等特殊字符進行<code>URLEncoder.encode(string,encodeCharset)</code>
* @param reqURL
*? ? ? ? ? ? 請求地址
* @param params
*? ? ? ? ? ? 請求參數(shù)
* @param encodeCharset
*? ? ? ? ? ? 編碼字符集,編碼請求數(shù)據(jù)時用之,其為null時默認采用UTF-8解碼
* @param decodeCharset
*? ? ? ? ? ? 解碼字符集,解析響應(yīng)數(shù)據(jù)時用之,其為null時默認采用UTF-8解碼
* @return 遠程主機響應(yīng)正文
*/
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>(); // 創(chuàng)建參數(shù)隊列
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) {
logger.debug("與[" + reqURL + "]通信過程中發(fā)生異常,堆棧信息如下", e);
} finally {
httpClient.getConnectionManager().shutdown();
}
return responseContent;
}
/**
* 發(fā)送HTTPS_POST請求
*
* @see 該方法為<code>sendPostSSLRequest(String,Map<String,String>,String,String)</code>方法的簡化方法
* @see 該方法在對請求數(shù)據(jù)的編碼和響應(yīng)數(shù)據(jù)的解碼時,所采用的字符集均為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);
}
/**
* 發(fā)送HTTPS_POST請求
*
* @see 該方法會自動關(guān)閉連接,釋放資源
* @see 該方法會自動對<code>params</code>中的[中文][|][
*? ? ? ]等特殊字符進行<code>URLEncoder.encode(string,encodeCharset)</code>
* @param reqURL
*? ? ? ? ? ? 請求地址
* @param params
*? ? ? ? ? ? 請求參數(shù)
* @param encodeCharset
*? ? ? ? ? ? 編碼字符集,編碼請求數(shù)據(jù)時用之,其為null時默認采用UTF-8解碼
* @param decodeCharset
*? ? ? ? ? ? 解碼字符集,解析響應(yīng)數(shù)據(jù)時用之,其為null時默認采用UTF-8解碼
* @return 遠程主機響應(yīng)正文
*/
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) {
logger.debug("與[" + reqURL + "]通信過程中發(fā)生異常,堆棧信息為", e);
} finally {
httpClient.getConnectionManager().shutdown();
}
return responseContent;
}
/**
* 發(fā)送HTTP_POST請求
*
* @see 若發(fā)送的<code>params</code>中含有中文,記得按照雙方約定的字符集將中文<code>URLEncoder.encode(string,encodeCharset)</code>
* @see 本方法默認的連接超時時間為30秒,默認的讀取超時時間為30秒
* @param reqURL
*? ? ? ? ? ? 請求地址
* @param params
*? ? ? ? ? ? 發(fā)送到遠程主機的正文數(shù)據(jù),其數(shù)據(jù)類型為<code>java.util.Map<String, String></code>
* @return 遠程主機響應(yīng)正文`HTTP狀態(tài)碼,如<code>"SUCCESS`200"</code><br>
*? ? ? ? 若通信過程中發(fā)生異常則返回"Failed`HTTP狀態(tài)碼",如<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());
}
/**
* 發(fā)送HTTP_POST請求
*
* @see 若發(fā)送的<code>sendData</code>中含有中文,記得按照雙方約定的字符集將中文<code>URLEncoder.encode(string,encodeCharset)</code>
* @see 本方法默認的連接超時時間為30秒,默認的讀取超時時間為30秒
* @param reqURL
*? ? ? ? ? ? 請求地址
* @param sendData
*? ? ? ? ? ? 發(fā)送到遠程主機的正文數(shù)據(jù)
* @return 遠程主機響應(yīng)正文`HTTP狀態(tài)碼,如<code>"SUCCESS`200"</code><br>
*? ? ? ? 若通信過程中發(fā)生異常則返回"Failed`HTTP狀態(tài)碼",如<code>"Failed`500"</code>
*/
public static String sendPostRequestByJava(String reqURL, String sendData) {
HttpURLConnection httpURLConnection = null;
OutputStream out = null; // 寫
InputStream in = null; // 讀
int httpStatusCode = 0; // 遠程主機響應(yīng)的HTTP狀態(tài)碼
try {
URL sendUrl = new URL(reqURL);
httpURLConnection = (HttpURLConnection) sendUrl.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true); // 指示應(yīng)用程序要將數(shù)據(jù)寫入URL連接,其值默認為false
httpURLConnection.setUseCaches(false);
httpURLConnection.setConnectTimeout(30000); // 30秒連接超時
httpURLConnection.setReadTimeout(30000); // 30秒讀取超時
out = httpURLConnection.getOutputStream();
out.write(sendData.toString().getBytes());
// 清空緩沖區(qū),發(fā)送數(shù)據(jù)
out.flush();
// 獲取HTTP狀態(tài)碼
httpStatusCode = httpURLConnection.getResponseCode();
in = httpURLConnection.getInputStream();
byte[] byteDatas = new byte[in.available()];
in.read(byteDatas);
return new String(byteDatas) + "`" + httpStatusCode;
} catch (Exception e) {
logger.debug(e.getMessage());
return "Failed`" + httpStatusCode;
} finally {
if (out != null) {
try {
out.close();
} catch (Exception e) {
logger.debug("關(guān)閉輸出流時發(fā)生異常,堆棧信息如下", e);
}
}
if (in != null) {
try {
in.close();
} catch (Exception e) {
logger.debug("關(guān)閉輸入流時發(fā)生異常,堆棧信息如下", e);
}
}
if (httpURLConnection != null) {
httpURLConnection.disconnect();
httpURLConnection = null;
}
}
}
/**
* https posp請求庆杜,可以繞過證書校驗
*
* @param url
* @param params
* @return
*/
public static final String sendHttpsRequestByPost(String url, Map<String, String> params) {
String responseContent = null;
HttpClient httpClient = new DefaultHttpClient();
// 創(chuàng)建TrustManager
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;
}
};
// 這個好像是HOST驗證
X509HostnameVerifier hostnameVerifier = new X509HostnameVerifier() {
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
public void verify(String arg0, SSLSocket arg1) throws IOException {
}
public void verify(String arg0, String[] arg1, String[] arg2) throws SSLException {
}
public void verify(String arg0, X509Certificate arg1) throws SSLException {
}
};
try {
// TLS1.0與SSL3.0基本上沒有太大的差別蚯根,可粗略理解為TLS是SSL的繼承者惊窖,但它們使用的是相同的SSLContext
SSLContext ctx = SSLContext.getInstance("TLS");
// 使用TrustManager來初始化該上下文,TrustManager只是被SSL的Socket所使用
ctx.init(null, new TrustManager[] { xtm }, null);
// 創(chuàng)建SSLSocketFactory
SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
socketFactory.setHostnameVerifier(hostnameVerifier);
// 通過SchemeRegistry將SSLSocketFactory注冊到我們的HttpClient上
httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", socketFactory, 443));
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> formParams = new ArrayList<NameValuePair>(); // 構(gòu)建POST請求的表單參數(shù)
for (Map.Entry<String, String> entry : params.entrySet()) {
formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity(); // 獲取響應(yīng)實體
if (entity != null) {
responseContent = EntityUtils.toString(entity, "UTF-8");
}
} catch (KeyManagementException e) {
logger.error("系統(tǒng)錯誤:",e);
} catch (NoSuchAlgorithmException e) {
logger.error("系統(tǒng)錯誤:",e);
} catch (UnsupportedEncodingException e) {
logger.error("系統(tǒng)錯誤:",e);
} catch (ClientProtocolException e) {
logger.error("系統(tǒng)錯誤:",e);
} catch (ParseException e) {
logger.error("系統(tǒng)錯誤:",e);
} catch (IOException e) {
logger.error("系統(tǒng)錯誤:",e);
} finally {
// 關(guān)閉連接,釋放資源
httpClient.getConnectionManager().shutdown();
}
return responseContent;
}
/**
* 發(fā)送HTTP_POST請求,json格式數(shù)據(jù)
*
* @param url
* @param body
* @return
* @throws Exception
*/
public static String sendPostByJson(String url, String body) throws Exception {
CloseableHttpClient httpclient = HttpClients.custom().build();
HttpPost post = null;
String resData = null;
CloseableHttpResponse result = null;
try {
post = new HttpPost(url);
HttpEntity entity2 = new StringEntity(body, Consts.UTF_8);
post.setConfig(RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(30000).build());
post.setHeader("Content-Type", "application/json");
post.setHeader("Access-Token", "sund2f3bf3e7ecea902bcdb7027e9139a02");
post.setEntity(entity2);
result = httpclient.execute(post);
if (HttpStatus.SC_OK == result.getStatusLine().getStatusCode()) {
resData = EntityUtils.toString(result.getEntity());
}
} finally {
if (result != null) {
result.close();
}
if (post != null) {
post.releaseConnection();
}
httpclient.close();
}
return resData;
}
/**
* HttpPost發(fā)送header,Content(json格式)
*
* @param url
* @param json
* @param headers
* @return
*/
public static String post(String url, Map<String, String> headers, Map<String, String> jsonMap) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
logger.info("請求地址:" + url);
// post.setHeader("Content-Type", "application/x-www-form-urlencoded");
logger.info("請求頭信息:" + headers);
if (headers != null) {
Set<String> keys = headers.keySet();
for (Map.Entry<String, String> entrdy : headers.entrySet()) {
post.addHeader(entrdy.getKey(), entrdy.getValue());
//System.out.println("headers:" + entrdy.getKey() + ",值" + entrdy.getValue());
}
}
String charset = null;
try {
StringEntity s = new StringEntity(jsonMap.toString(), "utf-8");
logger.info("請求json參數(shù):" + jsonMap);
// s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
// s.setContentType("application/json");
// s.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(s);
logger.info("請求實體數(shù)據(jù):" + post);
// HttpResponse res = client.execute(post);
HttpResponse httpResponse = client.execute(post);
InputStream inStream = httpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
StringBuilder strber = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
strber.append(line + "\n");
inStream.close();
logger.info("MobilpriseActivity:" + strber);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = httpResponse.getEntity();
charset = EntityUtils.getContentCharSet(entity);
}
} catch (Exception e) {
logger.info("報錯咯:" + e.getMessage());
throw new RuntimeException(e);
}
logger.info("響應(yīng)參數(shù):" + charset);
return charset;
}
public static void main(String[] args) {
try {
Map<String,String> headmap =? new HashMap<String,String>();
headmap.put("Access-Token", "sund2f3bf3e7ecea902bcdb7027e9139a02");
Map<String,String> paramap =? new HashMap<String,String>();
paramap.put("customerDeptId", "38");
paramap.put("postCode", "qqqq");
System.out.println(doPost("http://10.39.137.100/api/needs/getInfoByCondition",headmap,paramap));
//System.out.println(sendPostByJson("http://10.39.137.100/api/needs/getInfoByCondition","{\"customerDeptId\":38,\"postCode\":\"qqqq\"}"));
} catch (Exception e) {
logger.error("系統(tǒng)錯誤:",e);
}
}
}
?