HttpClient的Post和Get訪問網頁
阿新 • • 發佈:2019-01-31
package com.qidou.httpclient; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; 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.methods.HttpUriRequest; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; /** * HTTP請求客戶端,提供GET和POST兩種方式傳送請求。 * * @author Administrator * */ public class HttpClient { /** * 日誌物件。 */ private static Logger logger = Logger.getLogger(HttpClient.class); /** * 預設HTTP請求客戶端物件。 */ private DefaultHttpClient _httpclient; /** * 使用者自定義訊息頭。 */ private Map<String, String> _headers; /** * 使用預設客戶端物件。 */ public HttpClient() { // 1. 建立HttpClient物件。 _httpclient = new DefaultHttpClient(); logger.info("create _httpclient ..."); } /** * 呼叫者指定客戶端物件。 * * @param httpclient */ public HttpClient(Map<String, String> headers) { // 1. 建立HttpClient物件。 _httpclient = new DefaultHttpClient(); this._headers = headers; logger.info("create _httpclient ..."); } /** * HTTP POST請求。 * * @param url * @param params * @return * @throws InterruptedException */ public HttpResponse post(String url, Map<String, String> params) { // 2. 建立請求方法的例項,並指定請求URL,新增請求引數。 HttpPost post = postForm(url, params); logger.info("create httppost : " + url); return invoke(post); } /** * HTTP GET請求。 * * @param url * @return */ public HttpResponse get(String url) { HttpGet get = new HttpGet(url); logger.info("create httpget : " + url); return invoke(get); } /** * 傳送請求,處理響應。 * @param request * @return */ private HttpResponse invoke(HttpUriRequest request) { if (this._headers != null) { // addHeaders(request); logger.info("addHeaders to http ..."); } HttpResponse response = null; try { // 3. 呼叫HttpClient物件的execute(HttpUriRequest request)傳送請求,返回一個HttpResponse。 response = _httpclient.execute(request); logger.info("execute http success... ; body = " + EntityUtils.toString(response.getEntity())); } catch (Exception e) { e.printStackTrace(); logger.info("execute http exception..."); } finally { // 4. 無論執行方法是否成功,都必須釋放連線。 request.abort(); logger.info("release http ..."); } return response; } /** * 獲取post方法。 * * @param url * @param params * @return */ private HttpPost postForm(String url, Map<String, String> params) { HttpPost httpost = new HttpPost(url); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); // 組裝引數。 Set<String> keySet = params.keySet(); for (String key : keySet) { nvps.add(new BasicNameValuePair(key, params.get(key))); } try { logger.info("set utf-8 form entity to httppost ..."); httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return httpost; } /** * 增加訊息頭。 * * @param httpost */ private void addHeaders(HttpUriRequest httpost) { Iterator<Entry<String, String>> it = this._headers.entrySet() .iterator(); Entry<String, String> entry = null; String name = null; String value = null; while (it.hasNext()) { entry = it.next(); name = entry.getKey(); value = entry.getValue(); httpost.addHeader(name, value); } } /** * 關閉HTTP客戶端連結。 */ public void shutdown() { _httpclient.getConnectionManager().shutdown(); logger.info("shutdown _httpclient ..."); } }