httpclient—http和https的post請求;
阿新 • • 發佈:2018-11-05
最近我們好多專案使用了添加了ssl證書,用原來的方式做httpclient呼叫會出錯;
1.http:http工具類:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.URIException; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.httpclient.params.HttpConnectionManagerParams; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.commons.httpclient.util.URIUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.alibaba.fastjson.JSON; import com.ouyeel.util.BeanUtil; import com.ouyeel.util.JSONUtil; import com.ouyeel.util.StrUtil; public class HttpUtil { private static final Log log = LogFactory.getLog(HttpUtil.class); /** * 執行一個HTTP GET請求,返回請求響應的HTML * * @param url * 請求的URL地址 * @param queryString * 請求的查詢引數,可以為null * @param charset * 字符集 * @param pretty * 是否美化 * @return 返回請求響應的HTML */ public static String doGet(String url, String queryString, String charset, boolean pretty) { StringBuffer response = new StringBuffer(); HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); try { if (StrUtil.isNotBlank(queryString)) // 對get請求引數做了http請求預設編碼,好像沒有任何問題,漢字編碼後,就成為%式樣的字串 method.setQueryString(URIUtil.encodeQuery(queryString)); client.executeMethod(method); if (method.getStatusCode() == HttpStatus.SC_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset)); String line; while ((line = reader.readLine()) != null) { if (pretty) response.append(line).append(System.getProperty("line.separator")); else response.append(line); } reader.close(); } } catch (URIException e) { log.error("執行HTTP Get請求時,編碼查詢字串“" + queryString + "”發生異常!", e); } catch (IOException e) { log.error("執行HTTP Get請求" + url + "時,發生異常!", e); } finally { method.releaseConnection(); } return response.toString(); } /** * 執行一個HTTP GET請求,返回請求響應的HTML * * @param url * 請求的URL地址 * @param queryString * 請求的查詢引數,可以為null * @param charset * 字符集 * @param pretty * 是否美化 * @return 返回請求響應的HTML */ public static String doGet(String url, String queryString, Map<String, String> headers, String charset, boolean pretty) { StringBuffer response = new StringBuffer(); HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); if (BeanUtil.nonNull(headers)) { for (Map.Entry<String, String> entry : headers.entrySet()) { Header p = new Header(); p.setName(entry.getKey()); p.setValue(entry.getValue()); method.setRequestHeader(p); } } try { if (StrUtil.isNotBlank(queryString)) // 對get請求引數做了http請求預設編碼,好像沒有任何問題,漢字編碼後,就成為%式樣的字串 method.setQueryString(URIUtil.encodeQuery(queryString)); client.executeMethod(method); if (method.getStatusCode() == HttpStatus.SC_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset)); String line; while ((line = reader.readLine()) != null) { if (pretty) response.append(line).append(System.getProperty("line.separator")); else response.append(line); } reader.close(); } } catch (URIException e) { log.error("執行HTTP Get請求時,編碼查詢字串“" + queryString + "”發生異常!", e); } catch (IOException e) { log.error("執行HTTP Get請求" + url + "時,發生異常!", e); } finally { method.releaseConnection(); } return response.toString(); } /** * 執行一個HTTP POST請求,返回請求響應的HTML * * @param url * 請求的URL地址 * @param params * 請求的查詢引數,可以為null * @param charset * 字符集 * @param pretty * 是否美化 * @return 返回請求響應的HTML */ public static String doPostDataInParams(String url, Map<String, String> params, Map<String, String> headers, String charset, boolean pretty) { StringBuffer response = new StringBuffer(); HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); // 設定Http Post資料 if (BeanUtil.nonNull(params)) { List<NameValuePair> data = new ArrayList<NameValuePair>(); HttpMethodParams p = new HttpMethodParams(); for (Map.Entry<String, String> entry : params.entrySet()) { NameValuePair nameValuePair = new NameValuePair(); p.setParameter(entry.getKey(), entry.getValue()); nameValuePair.setName(entry.getKey()); nameValuePair.setValue(entry.getValue()); data.add(nameValuePair); method.setParameter(entry.getKey(), entry.getValue()); } method.setParams(p); NameValuePair[] datas = new NameValuePair[data.size()]; datas = data.toArray(datas); method.setRequestBody(datas); method.setQueryString(datas); } if (BeanUtil.nonNull(headers)) { for (Map.Entry<String, String> entry : headers.entrySet()) { Header p = new Header(); p.setName(entry.getKey()); p.setValue(entry.getValue()); method.setRequestHeader(p); } } try { client.executeMethod(method); if (method.getStatusCode() == HttpStatus.SC_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset)); String line; while ((line = reader.readLine()) != null) { if (pretty) response.append(line).append(System.getProperty("line.separator")); else response.append(line); } reader.close(); } } catch (IOException e) { log.error("執行HTTP Post請求" + url + "時,發生異常!", e); } finally { method.releaseConnection(); } return response.toString(); } /** * 執行一個HTTP POST請求,返回請求響應的HTML * * @param url * 請求的URL地址 * @param bodyDataObject * 請求的引數,可以為null,放在body裡 * @param charset * 字符集 * @param pretty * 是否美化 * @return 返回請求響應的HTML */ public static String doPostDataInBody(String url, Object bodyDataObject, Map<String, String> headers, String charset, boolean pretty) { StringBuffer response = new StringBuffer(); HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); // 設定Http Post資料 if (BeanUtil.nonNull(bodyDataObject)) { try { method.setRequestEntity(new StringRequestEntity(JSONUtil.toJson(bodyDataObject), "", "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } if (BeanUtil.nonNull(headers)) { for (Map.Entry<String, String> entry : headers.entrySet()) { Header p = new Header(); p.setName(entry.getKey()); p.setValue(entry.getValue()); method.setRequestHeader(p); } } method.setRequestHeader("Content-Type", "application/json"); try { client.executeMethod(method); if (method.getStatusCode() == HttpStatus.SC_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset)); String line; while ((line = reader.readLine()) != null) { if (pretty) response.append(line).append(System.getProperty("line.separator")); else response.append(line); } reader.close(); } } catch (IOException e) { log.error("執行HTTP Post請求" + url + "時,發生異常!", e); } finally { method.releaseConnection(); } return response.toString(); } public static String doPostResult(String urlStr, String params) throws Exception { System.out.println(urlStr); PostMethod postMethod = new PostMethod(urlStr); try { postMethod.addParameter("info", URLEncoder.encode(params, "UTF-8")); HttpClient client = new HttpClient(); postMethod.getParams().setParameter( HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");// 對含有中文的字元進行編碼 client.setConnectionTimeout(1000 * 60); // 設定超時時間 1分鐘 int status = 0; status = client.executeMethod(postMethod); if (status != 200) {// 連線失敗 // System.out.println("responseMsg:伺服器內部錯誤!!!"); throw new Exception("伺服器內部錯誤!!!"); } byte[] responseBody = postMethod.getResponseBody(); return new String(responseBody); } catch (Exception e) { e.printStackTrace(); throw new Exception(e); } finally { // 6.釋放連線 postMethod.releaseConnection(); } } public static Map doPost(String url ,String params) { Map map = new HashMap(); try { String jsonStr = URLDecoder.decode(doPostResult(url, params), "UTF-8"); if (StrUtil.isBlank(jsonStr)) return map; map = JSON.parseObject(jsonStr, Map.class); } catch (Exception e) { e.printStackTrace(); map.put("status", "fail"); map.put("msg", e.getMessage()); } return map; } public static String simplePostJsonInRequestBody1(String address, String str) throws Exception { HttpClient client = new HttpClient(); HttpConnectionManagerParams managerParams = client.getHttpConnectionManager().getParams(); HttpMethod method = getPostJsonMethodInRequestBod1(address, str);// 使用POST方式提交資料 client.setConnectionTimeout(60000); client.setTimeout(1200000); // 設定連線超時時間(單位毫秒) managerParams.setConnectionTimeout(60000); // 設定讀資料超時時間(單位毫秒) managerParams.setSoTimeout(1200000); client.executeMethod(method); String response=method.getResponseBodyAsString(); // String response = new String(method.getResponseBodyAsString().getBytes("ISO8859-1"), "UTF-8"); //System.out.println(response); method.releaseConnection(); return response; } private static HttpMethod getPostJsonMethodInRequestBod1(String address, String str) { PostMethod post = new PostMethod(address); post.addRequestHeader("Content-Type", "application/json; charset=utf-8"); post.setRequestBody(str); return post; } }
2.https doPost工具類;這裡使用了兩種方式;區別在於傳參和return引數;有時候傳參的方式會減少一些不必要的程式碼量;
dopost:引數傳遞後,獲取引數使用request.getParameter("name");
doPostMap: 引數接收方,直接可以在方法中傳遞引數 Method(String info)
import java.io.InputStream; import java.io.InputStreamReader; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.RequestEntity; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; import com.alibaba.fastjson.JSON; import com.google.common.io.CharStreams; public class HttpsUtil { /** * * @param json 引數 * @param url 請求url * @param encode 編碼 * @return String * */ public static String doPost(String json,String url,String encode) { ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory(); Protocol.registerProtocol("https", new Protocol("https", fcty, 443)); HttpClient client = new HttpClient(); // 使用POST方法 PostMethod method = new PostMethod( url); try { RequestEntity entity = new StringRequestEntity(json, "application/json", encode); method.setRequestEntity(entity); client.executeMethod(method); InputStream inputStream = method.getResponseBodyAsStream(); String restult = CharStreams.toString(new InputStreamReader(inputStream, "UTF-8")); return restult; } catch (Exception e) { e.printStackTrace(); } finally { // 釋放連線 method.releaseConnection(); } return null; } /** * * @param json 引數 * @param url 請求url * @param encode 編碼 * @return map */ public static Map doPostMap(String json,String url,String encode) { Map map = new HashMap(); ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory(); Protocol.registerProtocol("https", new Protocol("https", fcty, 443)); HttpClient client = new HttpClient(); // 使用POST方法 PostMethod method = new PostMethod( url); try { method.addParameter("info", URLEncoder.encode(json, encode)); method.getParams().setParameter( HttpMethodParams.HTTP_CONTENT_CHARSET, encode); client.setConnectionTimeout(1000 * 60); // 設定超時時間 1分鐘 client.executeMethod(method); InputStream inputStream = method.getResponseBodyAsStream(); String restult = CharStreams.toString(new InputStreamReader(inputStream, "UTF-8")); System.out.println("引數傳出:json:==============="+json); System.out.println("引數返回型別:=============================restult:"+restult); map = JSON.parseObject(restult, Map.class); return map; } catch (Exception e) { e.printStackTrace(); } finally { // 釋放連線 method.releaseConnection(); } return null; } }