Java中發送http的get、post請求

來源:互聯網
上載者:User

標籤:javascrip   ringbuf   抽取   pen   test   amp   input   return   for   

 

 近期做項目中,須要把訊息通過中介軟體的形式通過http請求的方式推送給第三方,因此用到了http協議,小編花費了一個多小時。對於http協議中的post和get請求,封裝了一個工具類。以下與大家分享一下。

有不好的地方請多多不吝賜教。

/**      * @FileName: HttpTest.java    * @Package:com.io    * @Description: TODO   * @author: LUCKY     * @date:2016年1月6日 下午3:49:28    * @version V1.0      */package com.io;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLEncoder;import java.security.SecureRandom;import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import java.util.HashMap;import java.util.Map;import java.util.Map.Entry;import java.util.Set;import javax.net.ssl.HostnameVerifier;import javax.net.ssl.HttpsURLConnection;import javax.net.ssl.KeyManager;import javax.net.ssl.SSLContext;import javax.net.ssl.SSLSession;import javax.net.ssl.TrustManager;import javax.net.ssl.X509TrustManager;import com.alibaba.common.lang.StringUtil;/** * @ClassName: HttpTest * @Description: 自己開始封裝的HTTP串連工具,http串連傳遞的參數封裝到一個對象裡面, *               http中get請求時,是把參數拼接到url後面的,而post請求直接輸出就可以 * @author: LUCKY * @date:2016年1月6日 下午3:49:28 */public class HttpTest {private static final String METHOD_POST = "POST";private static final String METHOD_GET = "GET";private static final String DEFAULT_CHARSET = "UTF-8";private static final String HTTPS = "https";private static final String TLS = "tls";private static final String CTYPE = "application/x-www-form-urlencoded;charset="+ DEFAULT_CHARSET;public static void main(String[] args) throws Exception {Map<String, String> param = new HashMap<String, String>();param.put("body", String.valueOf(System.currentTimeMillis()));param.put("tag", "撒點粉");String string = doGet("http://localhost/receive.do", param,3000, 3000);String aa = doPost("http://localhost/receive.do", param,3000, 3000);System.out.println(string.length());System.out.println(string);}/** * @throws Exception * @Title: doPost * @Description: doPost發送請求操作 * @param @param url * @param @param params * @param @param readTimeOut * @param @param connectTimeOut * @param @return * @return String * @throws */public static String doPost(String url, Map<String, String> params,int readTimeOut, int connectTimeOut) throws Exception {HttpURLConnection connection = null;OutputStream out = null;String result = null;try {connection = getConnection(new URL(url), readTimeOut,connectTimeOut, METHOD_POST, CTYPE, null);byte[] content = new byte[0];String param = getUrl(params, DEFAULT_CHARSET);if (StringUtil.isNotEmpty(param)) {content = param.getBytes(DEFAULT_CHARSET);}out = connection.getOutputStream();// post傳送訊息內容out.write(content);// 接受的傳回值通過buffer來接受result = responseAsString(connection);} catch (IOException e) {e.printStackTrace();throw e;} finally {if (connection != null) {connection.disconnect();}}return result;}/** * @Title: doGet * @Description: doGet發送訊息請求 * @param @param url * @param @param params * @param @param readTimeOut * @param @param connectTimeOut * @param @return * @return String * @throws */public static String doGet(String url, Map<String, String> params,int readTimeOut, int connectTimeOut) {HttpURLConnection connection = null;String result=null;try {String query = getUrl(params, DEFAULT_CHARSET);connection = getConnection(new URL(buildUrl(url, query)),readTimeOut, connectTimeOut, METHOD_GET, CTYPE, null);       result=responseAsString(connection);} catch (Exception e) {e.printStackTrace();} finally {if (connection != null) {connection.disconnect();}}return result;}// 把doGet和doPost請求最後的接受參數再次的抽取出來private static String responseAsString(HttpURLConnection connection) {StringBuffer buffer = new StringBuffer();InputStreamReader reader = null;OutputStream out = null;try {// 假設返回成功if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {reader = new InputStreamReader(connection.getInputStream());char[] ch = new char[1024];int x = 0;while ((x = reader.read(ch)) != -1) {buffer.append(ch, 0, x);}}} catch (Exception e) {e.printStackTrace();} finally {if (connection != null) {connection.disconnect();}}return buffer.toString();}// 須要再寫一個getConnection的方法,把doPost和doGet的connection都抽取出來private static HttpURLConnection getConnection(URL url, int readTimeOut,int connectTimeOut, String method, String ctype,Map<String, String> headMap) throws Exception {HttpURLConnection connection = null;if (url == null) {return null;}if (HTTPS.equals(url.getProtocol())) {SSLContext ctx = null;try {ctx = SSLContext.getInstance(TLS);ctx.init(new KeyManager[0],new TrustManager[] { new DefaultTrustManager() },new SecureRandom());} catch (Exception e) {throw new IOException(e);}HttpsURLConnection connHttps = (HttpsURLConnection) url.openConnection();connHttps.setSSLSocketFactory(ctx.getSocketFactory());connHttps.setHostnameVerifier(new HostnameVerifier() {public boolean verify(String hostname, SSLSession session) {return true;}});connection = connHttps;} else {connection = (HttpURLConnection) url.openConnection();}connection.setReadTimeout(readTimeOut);connection.setDoInput(true);connection.setDoOutput(true);connection.setRequestMethod(method);connection.setConnectTimeout(connectTimeOut);connection.setRequestProperty("Accept","text/xml,text/javascript,text/html");connection.setRequestProperty("User-Agent", "top-sdk-java");connection.setRequestProperty("Content-Type", ctype);// 遍曆設定headMapif (null != headMap) {Set<Entry<String, String>> entries = headMap.entrySet();for (Map.Entry<String, String> entry : entries) {connection.setRequestProperty(entry.getKey(), entry.getValue());}}return connection;}/** * @Title: getUrl * @Description: doGet發送請求時拼接的URL * @param @param params * @param @param charset * @param @return * @param @throws UnsupportedEncodingException * @return String * @throws */public static String getUrl(Map<String, String> params, String charset)throws UnsupportedEncodingException {StringBuffer buffer = new StringBuffer("?");if (params == null && params.isEmpty()) {return null;}// 否則的話,開始拼接須要傳遞的值。也就是URL?AA==BB&CC==EE這種相似的串連值Set<Entry<String, String>> entries = params.entrySet();for (Entry<String, String> entry : entries) {String name = entry.getKey();String value = entry.getValue();// 還須要進行一次推斷是否為空白,一定要謹慎if (StringUtil.isNotEmpty(name) && StringUtil.isNotEmpty(value)) {// 假設不為空白的話。開始進行串連操作buffer.append("&").append(name).append("=").append(URLEncoder.encode(value, charset));}}return buffer.toString().substring(0, buffer.toString().length() - 1);}/** * @Title: buildUrl * @Description: 拼接url地址操作 * @param @param url * @param @param query * @param @return * @return String * @throws */private static String buildUrl(String url, String query) {if (query == null && query.isEmpty()) {return url;}if (url.endsWith("?")) {url = url + query;} else {url = url + "?

" + query;}return url;}private static class DefaultTrustManager implements X509TrustManager {public X509Certificate[] getAcceptedIssuers() {return null;}public void checkClientTrusted(X509Certificate[] chain, String authType)throws CertificateException {}public void checkServerTrusted(X509Certificate[] chain, String authType)throws CertificateException {}}}



 很多其它有關http協議的內容,請參考:Http協議具體解釋

                                                           Http協議中的Content-Type

Java中發送http的get、post請求

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.