java http 請求, 通過HTTPClient這種第三方的開源架構去實現.__http

來源:互聯網
上載者:User
工作中用到的一個http請求工具類

package com.qiantu.core.utils;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.security.KeyStore;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;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.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.util.EntityUtils;import com.alibaba.fastjson.JSON;/** * @date 2015-05-31 上午9:56:10 * @author xuning *  */public class HttpUtil {private static final String DEFAULT_ENCODING = "UTF-8";/** * GET方式請求 *  * @param uri *            伺服器的uri要用物理IP或網域名稱,不識別localhost或127.0.0.1形式! * @return * @throws IOException * @throws ClientProtocolException */public static String get(String uri) throws ClientProtocolException,IOException {HttpGet httpGet = new HttpGet(uri);HttpClient httpClient = new DefaultHttpClient();HttpResponse httpResponse = httpClient.execute(httpGet);int statusCode;if ((statusCode = httpResponse.getStatusLine().getStatusCode()) == 200) {String result = EntityUtils.toString(httpResponse.getEntity());return EntityUtils.toString(httpResponse.getEntity());}throw new IOException("status is " + statusCode);}/** * GET方式請求 *  * @param uri *            伺服器的uri要用物理IP或網域名稱,不識別localhost或127.0.0.1形式! * @return * @throws IOException * @throws ClientProtocolException */public static String get(String uri, Map<String, String> paramMap)throws ClientProtocolException, IOException {StringBuilder sb = new StringBuilder(uri);if (paramMap != null) {boolean isBegin = true;for (String key : paramMap.keySet()) {if (isBegin) {sb.append("?").append(key).append("=").append(paramMap.get(key));isBegin = false;} else {sb.append("&").append(key).append("=").append(paramMap.get(key));}}}HttpGet httpGet = new HttpGet(sb.toString());HttpClient httpClient = new DefaultHttpClient();HttpResponse httpResponse = httpClient.execute(httpGet);int statusCode;if ((statusCode = httpResponse.getStatusLine().getStatusCode()) == 200) {//String result = EntityUtils.toString(httpResponse.getEntity());return EntityUtils.toString(httpResponse.getEntity());}throw new IOException("status is " + statusCode);}/** * GET方式請求https *  * @param uri *            伺服器的uri要用物理IP或網域名稱,不識別localhost或127.0.0.1形式! * @return * @throws IOException * @throws ClientProtocolException */public static String httpsGet(String uri, String keyFile, String keyPwd)throws Exception {HttpGet httpGet = new HttpGet(uri);HttpClient httpClient = newHttpsClient(keyFile, keyPwd);HttpResponse httpResponse = httpClient.execute(httpGet);int statusCode;if ((statusCode = httpResponse.getStatusLine().getStatusCode()) == 200) {//String result = EntityUtils.toString(httpResponse.getEntity(),//DEFAULT_ENCODING);return  EntityUtils.toString(httpResponse.getEntity(),DEFAULT_ENCODING);}throw new IOException("status is " + statusCode);}/** * POST方式請求 *  * @param uri *            伺服器的uri要用物理IP或網域名稱,不識別localhost或127.0.0.1形式! * @param paramMap * @return * @throws IOException * @throws ClientProtocolException */public static String post(String uri, Map<String, String> paramMap)throws ClientProtocolException, IOException {HttpPost httpPost = new HttpPost(uri);List<NameValuePair> params = new ArrayList<NameValuePair>();if (paramMap != null) {for (String key : paramMap.keySet()) {params.add(new BasicNameValuePair(key, paramMap.get(key)));}httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));}HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost);int statusCode;if ((statusCode = httpResponse.getStatusLine().getStatusCode()) == 200) {return EntityUtils.toString(httpResponse.getEntity(),DEFAULT_ENCODING);}throw new IOException("status is " + statusCode);}/** * POST方式請求,UTF-8編碼發送內容 *  * @param uri * @param paramMap * @return * @throws ClientProtocolException * @throws IOException */public static String postEncoding(String uri, Map<String, String> paramMap)throws ClientProtocolException, IOException {HttpPost httpPost = new HttpPost(uri);List<NameValuePair> params = new ArrayList<NameValuePair>();if (paramMap != null) {for (String key : paramMap.keySet()) {params.add(new BasicNameValuePair(key, paramMap.get(key)));}httpPost.setEntity(new UrlEncodedFormEntity(params,DEFAULT_ENCODING));}HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost);int statusCode;if ((statusCode = httpResponse.getStatusLine().getStatusCode()) == 200) {return EntityUtils.toString(httpResponse.getEntity(),DEFAULT_ENCODING);}throw new IOException("status is " + statusCode);}/** * POST方式請求 *  * @param uri *            伺服器的uri要用物理IP或網域名稱,不識別localhost或127.0.0.1形式! * @param paramMap * @param headers * @return * @throws ClientProtocolException * @throws IOException */public static String post(String uri, Map<String, String> paramMap,Map<String, String> headers) throws ClientProtocolException,IOException {HttpPost httpPost = new HttpPost(uri);if (headers != null) {for (String key : headers.keySet()) {httpPost.setHeader(key, headers.get(key));}}List<NameValuePair> params = new ArrayList<NameValuePair>();if (paramMap != null) {for (String key : paramMap.keySet()) {params.add(new BasicNameValuePair(key, paramMap.get(key)));}httpPost.setEntity(new UrlEncodedFormEntity(params,DEFAULT_ENCODING));}HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost);int statusCode;if ((statusCode = httpResponse.getStatusLine().getStatusCode()) == 200) {return EntityUtils.toString(httpResponse.getEntity(),DEFAULT_ENCODING);}throw new IOException("status is " + statusCode);}/** * POST方式請求https *  * @param uri *            伺服器的uri要用物理IP或網域名稱,不識別localhost或127.0.0.1形式! * @param paramMap * @return * @throws IOException * @throws ClientProtocolException */public static String httpsPost(String uri, Map<String, String> paramMap,String keyFile, String keyPwd) throws ClientProtocolException,IOException, Exception {HttpPost httpPost = new HttpPost(uri);List<NameValuePair> params = new ArrayList<NameValuePair>();if (paramMap != null) {for (String key : paramMap.keySet()) {params.add(new BasicNameValuePair(key, paramMap.get(key)));}httpPost.setEntity(new UrlEncodedFormEntity(params,DEFAULT_ENCODING));}HttpResponse httpResponse = newHttpsClient(keyFile, keyPwd).execute(httpPost);int statusCode;if ((statusCode = httpResponse.getStatusLine().getStatusCode()) == 200) {return EntityUtils.toString(httpResponse.getEntity());}throw new IOException("status is " + statusCode);}/* * 建立httpsClient */private static HttpClient newHttpsClient(String keyFile, String keyPwd)throws Exception {KeyStore trustStore = KeyStore.getInstance("BKS");trustStore.load(new FileInputStream(new File(keyFile)),keyPwd.toCharArray());SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);Scheme sch = new Scheme("https", socketFactory, 8443);HttpClient client = new DefaultHttpClient();client.getConnectionManager().getSchemeRegistry().register(sch);return client;}/** * post請求發送傳輸obj對象 *  * @param uri * @param paramMap * @return * @throws ClientProtocolException * @throws IOException */public static String postOfObject(String uri, Object obj)throws ClientProtocolException, IOException {String params = JSON.toJSONString(obj);return HttpUtil.postJson(uri, params);}/** * 針對http傳輸json資料處理 *  * @param uri * @param parameters * @return * @throws ClientProtocolException * @throws IOException */public static String postJson(String uri, String parameters)throws ClientProtocolException, IOException {HttpPost httpPost = new HttpPost(uri);if (parameters != null) {StringEntity entity = new StringEntity(parameters);entity.setContentEncoding("UTF-8");entity.setContentType("application/json");httpPost.setEntity(entity);}HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost);int statusCode;if ((statusCode = httpResponse.getStatusLine().getStatusCode()) == 200) {return EntityUtils.toString(httpResponse.getEntity(),DEFAULT_ENCODING);}throw new IOException("status is " + statusCode);}/** * 針對http傳輸json資料處理 *  * @param uri * @param parameters * @return * @throws ClientProtocolException * @throws IOException */public static String postByJson(String uri, String parameters)throws ClientProtocolException, IOException {HttpPost httpPost = new HttpPost(uri);if (parameters != null) {StringEntity entity = new StringEntity(parameters,"UTF-8");entity.setContentEncoding("UTF-8");entity.setContentType("application/json");httpPost.setEntity(entity);}HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost);int statusCode;if ((statusCode = httpResponse.getStatusLine().getStatusCode()) == 200) {return EntityUtils.toString(httpResponse.getEntity(),DEFAULT_ENCODING);}throw new IOException("status is " + statusCode);}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.