HttpClient服務端的請求

來源:互聯網
上載者:User

標籤:http   java   os   io   資料   for   ar   art   

import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.Reader;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.net.SocketTimeoutException;import java.net.URL;import java.net.URLEncoder;import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Map.Entry;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.HttpVersion;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.client.params.HttpClientParams;import org.apache.http.conn.ClientConnectionManager;import org.apache.http.conn.ConnectTimeoutException;import org.apache.http.conn.params.ConnManagerParams;import org.apache.http.conn.params.ConnPerRouteBean;import org.apache.http.conn.scheme.PlainSocketFactory;import org.apache.http.conn.scheme.Scheme;import org.apache.http.conn.scheme.SchemeRegistry;import org.apache.http.conn.ssl.SSLSocketFactory;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;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.params.HttpProtocolParams;import org.apache.http.protocol.HTTP;/** * 最佳化httpclient,解決安全執行緒,重複串連池等效能問題。 *  * */public class HttpUtils {private final static boolean DEBUG = false;public final static String CHARSET = "UTF-8";/** * 這定義了通過網路與伺服器建立串連的逾時時間。 Httpclient包中通過一個非同步線程去建立與伺服器的socket串連 * ,這就是該socket串連的逾時時間(毫秒) */public final static int DEFAULT_SOCKET_TIMEOUT = 2000;/** 這定義了Socket讀資料的逾時時間,即從伺服器擷取響應資料需要等待的時間(毫秒) */public final static int WAIT_GETDATA_TIME = 4000;/** 配置每台主機最多串連數 */public final static int DEFAULT_HOST_CONNECTIONS = 50;/** 和串連池中的最多串連總數 */public final static int DEFAULT_MAX_CONNECTIONS = 50;/** Socket 緩衝大小 */public final static int DEFAULT_SOCKET_BUFFER_SIZE = 8192;/** 這定義了從ConnectionManager管理的串連池中取出串連的逾時時間(毫秒) */public final static int GET_CONNECT_TIME = 1000;private static HttpClient httpClient = null;private static synchronized HttpClient getHttpClient() {if (httpClient == null) {final HttpParams httpParams = new BasicHttpParams();ConnManagerParams.setTimeout(httpParams, GET_CONNECT_TIME);HttpConnectionParams.setConnectionTimeout(httpParams, DEFAULT_SOCKET_TIMEOUT);HttpConnectionParams.setSoTimeout(httpParams, WAIT_GETDATA_TIME);ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(DEFAULT_HOST_CONNECTIONS));ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);/** 以先發送部分請求(如:只發送要求標頭)進行試探,如果伺服器願意接收,則繼續發送請求體 */HttpProtocolParams.setUseExpectContinue(httpParams, true);/** * 即在有傳輸資料需求時,會首先檢查串連池中是否有可供重用的串連,如果有,則會重用串連。 * 同時,為了確保該“被重用”的串連確實有效,會在重用之前對其進行有效性檢查 */HttpConnectionParams.setStaleCheckingEnabled(httpParams, false);HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);HttpProtocolParams.setContentCharset(httpParams, HTTP.UTF_8);HttpClientParams.setRedirecting(httpParams, false);// 設定代理String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6";HttpProtocolParams.setUserAgent(httpParams, userAgent);// disable Nagle algorithmHttpConnectionParams.setTcpNoDelay(httpParams, true);HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);// 配置 http and httpsSchemeRegistry schemeRegistry = new SchemeRegistry();schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));ClientConnectionManager manager = new ThreadSafeClientConnManager(httpParams, schemeRegistry);httpClient = new DefaultHttpClient(manager, httpParams);}return httpClient;}public static InputStream doHttpClientPost(String url, HashMap<String, String> params) {if (DEBUG) {System.out.println("doPost url is " + url);}HttpClient httpClient = getHttpClient();HttpPost httpRequest = new HttpPost(url);List<BasicNameValuePair> httpParams = new ArrayList<BasicNameValuePair>();Iterator<Entry<String, String>> iter = params.entrySet().iterator();while (iter.hasNext()) {Map.Entry<String, String> entry = iter.next();String key = entry.getKey();String val = entry.getValue();httpParams.add(new BasicNameValuePair(key, val));}InputStream inputStream = null;String erroMsg = null;try {httpRequest.setEntity(new UrlEncodedFormEntity(httpParams, HTTP.UTF_8));} catch (UnsupportedEncodingException e) {}HttpResponse httpResponse = null;try {httpResponse = httpClient.execute(httpRequest);} catch (ClientProtocolException e) {erroMsg = e.getMessage().toString();e.printStackTrace();} catch (IOException e) {erroMsg = e.getMessage().toString();e.printStackTrace();}int statusCode = httpResponse.getStatusLine().getStatusCode();if (statusCode == 200) {try {inputStream = httpResponse.getEntity().getContent();} catch (IllegalStateException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}} else {erroMsg = "Error Response: " + httpResponse.getStatusLine().toString();}if (erroMsg != null) {System.out.println("doPost error, error message is " + erroMsg);}return inputStream;}public static InputStream doHttpsClientPost(String url, String params) {if (DEBUG) {System.out.println("doPost url is " + url);}HttpClient httpClient = getHttpClient();HttpPost httpRequest = new HttpPost(url);InputStream inputStream = null;String erroMsg = null;try {HttpEntity entity = new StringEntity(params,"utf-8");httpRequest.setEntity(entity);} catch (UnsupportedEncodingException e) {}HttpResponse httpResponse = null;try {httpResponse = httpClient.execute(httpRequest);} catch (ClientProtocolException e) {erroMsg = e.getMessage().toString();e.printStackTrace();} catch (IOException e) {erroMsg = e.getMessage().toString();e.printStackTrace();}int statusCode = httpResponse.getStatusLine().getStatusCode();if (statusCode == 200) {try {inputStream = httpResponse.getEntity().getContent();} catch (IllegalStateException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}} else {erroMsg = "Error Response: " + httpResponse.getStatusLine().toString();}if (erroMsg != null) {System.out.println("doPost error, error message is " + erroMsg);}return inputStream;}public static InputStream doHttpClientGet(String url, HashMap<String, String> params) {HttpClient httpClient = getHttpClient();if (DEBUG) {System.out.println("doGet the url before encode is " + url);}if (params != null) {String paramStr = "";try {Iterator<Entry<String, String>> iter = params.entrySet().iterator();while (iter.hasNext()) {Map.Entry<String, String> entry = iter.next();String key = entry.getKey();key = URLEncoder.encode(key, "UTF-8");String val = entry.getValue();val = URLEncoder.encode(val, "UTF-8");paramStr += paramStr = "&" + key + "=" + val;}} catch (UnsupportedEncodingException e1) {e1.printStackTrace();}if (!paramStr.equals("")) {paramStr = paramStr.replaceFirst("&", "?");url += paramStr;}}if (DEBUG) {System.out.println("doGet the url after encode is " + url);}HttpGet httpRequest = null;try {httpRequest = new HttpGet(url);} catch (IllegalArgumentException e) {System.out.println("uri argument error");return null;}InputStream inputStream = null;HttpResponse httpResponse = null;try {httpResponse = httpClient.execute(httpRequest);} catch (IllegalStateException e) {e.printStackTrace();} catch (ClientProtocolException e) {e.printStackTrace();} catch (SocketTimeoutException e) {e.printStackTrace();} catch (ConnectTimeoutException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}if (httpResponse == null) {System.out.println("no response from server");return null;}if (httpResponse.getStatusLine().getStatusCode() == 200) {HttpEntity httpEntity = httpResponse.getEntity();try {inputStream = httpEntity.getContent();} catch (IllegalStateException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}} else {System.out.println("Error Response: " + httpResponse.getStatusLine().toString());}return inputStream;}// 未經最佳化的原聲方法public static String doHttpURLConnection(String myurl) throws IOException {InputStream is = null;// Only display the first 1000 characters of the retrieved// web page content.int len = 1000;try {URL url = new URL(myurl);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setReadTimeout(10000 /* milliseconds */);conn.setConnectTimeout(15000 /* milliseconds */);conn.setRequestMethod("GET");conn.setDoInput(true);// Starts the queryconn.connect();int response = conn.getResponseCode();if (DEBUG) {System.out.println("The response is: " + response);}is = conn.getInputStream();// Convert the InputStream into a stringString contentAsString = readIt(is, len);return contentAsString;// Makes sure that the InputStream is closed after the app is// finished using it.} finally {if (is != null) {is.close();}}}// Reads an InputStream and converts it to a String.public static String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {if (stream == null)return null;Reader reader = null;reader = new InputStreamReader(stream, "UTF-8");char[] buffer = new char[len];reader.read(buffer);return new String(buffer);}}


聯繫我們

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