1. 程式人生 > >apache httpclient 4 學習和例子

apache httpclient 4 學習和例子

package com.eecn.warehouse.api.action;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class HttpTest {

	    public final static void main(String[] args) throws Exception {
	 
	        // 初始化,此處建構函式就與3.1中不同
	        HttpClient httpclient = new DefaultHttpClient();
	 
	        HttpHost targetHost = new HttpHost("www.google.com.hk");
	        //HttpGet httpget = new HttpGet("http://www.apache.org/");
	        HttpGet httpget = new HttpGet("/");
	 
	        // 檢視預設request頭部資訊
	        System.out.println("Accept-Charset:" + httpget.getFirstHeader("Accept-Charset"));
	        // 以下這條如果不加會發現無論你設定Accept-Charset為gbk還是utf-8,他都會預設返回gb2312(本例針對google.cn來說)
	        httpget.setHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.2)");
	        // 用逗號分隔顯示可以同時接受多種編碼
	        httpget.setHeader("Accept-Language", "zh-cn,zh;q=0.5");
	        httpget.setHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");
	        // 驗證頭部資訊設定生效
	        System.out.println("Accept-Charset:" + httpget.getFirstHeader("Accept-Charset").getValue());
	 
	        // Execute HTTP request
	        System.out.println("executing request " + httpget.getURI());
	        HttpResponse response = httpclient.execute(targetHost, httpget);
	        //HttpResponse response = httpclient.execute(httpget);
	 
	        System.out.println("----------------------------------------");
	        System.out.println("Location: " + response.getLastHeader("Location"));
	        System.out.println(response.getStatusLine().getStatusCode());
	        System.out.println(response.getLastHeader("Content-Type"));
	        System.out.println(response.getLastHeader("Content-Length"));
	        
	        System.out.println("----------------------------------------");
	 
	        // 判斷頁面返回狀態判斷是否進行轉向抓取新連結
	        int statusCode = response.getStatusLine().getStatusCode();
	        if ((statusCode == HttpStatus.SC_MOVED_PERMANENTLY) ||
	                (statusCode == HttpStatus.SC_MOVED_TEMPORARILY) ||
	                (statusCode == HttpStatus.SC_SEE_OTHER) ||
	                (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
	            // 此處重定向處理  此處還未驗證
	            String newUri = response.getLastHeader("Location").getValue();
	            httpclient = new DefaultHttpClient();
	            httpget = new HttpGet(newUri);
	            response = httpclient.execute(httpget);
	        }
	 
	        // Get hold of the response entity
	        HttpEntity entity = response.getEntity();
	        
	        // 檢視所有返回頭部資訊
	        Header headers[] = response.getAllHeaders();
	        int ii = 0;
	        while (ii < headers.length) {
	            System.out.println(headers[ii].getName() + ": " + headers[ii].getValue());
	            ++ii;
	        }
	        
	        // If the response does not enclose an entity, there is no need
	        // to bother about connection release
	        if (entity != null) {
	            // 將原始碼流儲存在一個byte陣列當中,因為可能需要兩次用到該流,
	            byte[] bytes = EntityUtils.toByteArray(entity);
	            String charSet = "";
	            
	            // 如果頭部Content-Type中包含了編碼資訊,那麼我們可以直接在此處獲取
	            charSet = ContentType.getOrDefault(entity).getCharset().name();
	 
	            System.out.println("In header: " + charSet);
	            // 如果頭部中沒有,那麼我們需要 檢視頁面原始碼,這個方法雖然不能說完全正確,因為有些粗糙的網頁編碼者沒有在頁面中寫頭部編碼資訊
	            if (charSet == "") {
	                String regEx = "(?=<meta).*?(?<=charset=[\\'|\\\"]?)([[a-z]|[A-Z]|[0-9]|-]*)";
	                Pattern p = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
	                Matcher m = p.matcher(new String(bytes));  // 預設編碼轉成字串,因為我們的匹配中無中文,所以串中可能的亂碼對我們沒有影響
	                boolean result = m.find();
	                System.out.println(result);
	                if (m.groupCount() == 1) {
	                    charSet = m.group(1);
	                } else {
	                    charSet = "";
	                }
	            }
	            System.out.println("Last get: " + charSet);
	            // 至此,我們可以將原byte陣列按照正常編碼專成字串輸出(如果找到了編碼的話)
	            System.out.println("Encoding string is: " + new String(bytes, charSet));
	        }
	 
	        httpclient.getConnectionManager().shutdown();        
	    }
	 
}

下面是也是一個例子:

public static String sendRequest(String[] reqXml) {
		HttpPost httpPost = null;
		String rspXml = null;
		try {
			// 構造HttpClient的例項
			HttpClient httpClient = new DefaultHttpClient();
			
			// 設定連線超時
			httpClient.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 10000);
			httpClient.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, 20000);
			httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
			
			httpPost = new HttpPost(ApiAction.SERVER_URL);
			
			//httpPost.setHeader(HTTP.CONTENT_TYPE, "charset=UTF-8");
			httpPost.setHeader(HTTP.CONTENT_ENCODING, "UTF-8");
			httpPost.setHeader(HTTP.USER_AGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.2)");
	        // 用逗號分隔顯示可以同時接受多種編碼
			httpPost.setHeader("Accept-Language", "zh-cn,zh;q=0.5");
			httpPost.setHeader("Accept-Charset", "UTF-8;q=0.7,*;q=0.7");
			
			//引數
			List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
			nameValuePairList.add(new BasicNameValuePair("xml", reqXml[0]));
			nameValuePairList.add(new BasicNameValuePair("signature", reqXml[1]));
			
			// 將引數加入到請求方法中
			HttpEntity httpEntity = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");
			httpPost.setEntity(httpEntity);
			
			// 傳送連線
			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity rspHttpEntity = httpResponse.getEntity();

			int statusCode = httpResponse.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {
				rspXml = IOUtils.toString(rspHttpEntity.getContent());
				LOGGER.info("響應XML:" + rspXml);
			} else {
				LOGGER.error("http client 錯誤。錯誤碼[" + statusCode + "]");
			}
			return rspXml;
		} catch (Exception e) {
			LOGGER.error("http client invoke error.", e);
			return null;
		} finally {
			if (httpPost != null) {
				httpPost.releaseConnection();
			}
		}
	}