httputil

?

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);

}

}

}

?

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末斗躏,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌握联,老刑警劉巖,帶你破解...
    沈念sama閱讀 212,816評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件每瞒,死亡現(xiàn)場離奇詭異金闽,居然都是意外死亡,警方通過查閱死者的電腦和手機剿骨,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,729評論 3 385
  • 文/潘曉璐 我一進店門代芜,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人浓利,你說我怎么就攤上這事挤庇。” “怎么了贷掖?”我有些...
    開封第一講書人閱讀 158,300評論 0 348
  • 文/不壞的土叔 我叫張陵嫡秕,是天一觀的道長。 經(jīng)常有香客問我羽资,道長淘菩,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,780評論 1 285
  • 正文 為了忘掉前任屠升,我火速辦了婚禮潮改,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘腹暖。我一直安慰自己汇在,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 65,890評論 6 385
  • 文/花漫 我一把揭開白布脏答。 她就那樣靜靜地躺著糕殉,像睡著了一般亩鬼。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上阿蝶,一...
    開封第一講書人閱讀 50,084評論 1 291
  • 那天雳锋,我揣著相機與錄音,去河邊找鬼羡洁。 笑死玷过,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的筑煮。 我是一名探鬼主播辛蚊,決...
    沈念sama閱讀 39,151評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼真仲!你這毒婦竟也來了袋马?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,912評論 0 268
  • 序言:老撾萬榮一對情侶失蹤秸应,失蹤者是張志新(化名)和其女友劉穎虑凛,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體软啼,經(jīng)...
    沈念sama閱讀 44,355評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡卧檐,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,666評論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了焰宣。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,809評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡捕仔,死狀恐怖匕积,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情榜跌,我是刑警寧澤闪唆,帶...
    沈念sama閱讀 34,504評論 4 334
  • 正文 年R本政府宣布,位于F島的核電站钓葫,受9級特大地震影響悄蕾,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜础浮,卻給世界環(huán)境...
    茶點故事閱讀 40,150評論 3 317
  • 文/蒙蒙 一帆调、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧豆同,春花似錦番刊、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,882評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽蝉绷。三九已至,卻和暖如春枣抱,著一層夾襖步出監(jiān)牢的瞬間熔吗,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,121評論 1 267
  • 我被黑心中介騙來泰國打工佳晶, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留桅狠,地道東北人。 一個月前我還...
    沈念sama閱讀 46,628評論 2 362
  • 正文 我出身青樓宵晚,卻偏偏與公主長得像垂攘,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子淤刃,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 43,724評論 2 351