1. 程式人生 > >HttpClient 傳送Post Get請求例子 包含設定請求頭資訊和獲取返回頭資訊

HttpClient 傳送Post Get請求例子 包含設定請求頭資訊和獲取返回頭資訊

               
package com.test.action;import java.io.IOException;import java.util.ArrayList;import java.util.List;import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;import org.apache.commons.httpclient.Header;import org.apache.commons.httpclient.HttpClient;import org.apache.commons.httpclient.HttpException;import
org.apache.commons.httpclient.HttpStatus;import org.apache.commons.httpclient.methods.PostMethod;import org.apache.commons.httpclient.params.HttpMethodParams;/*** * 依賴 commons-httpclient-3.1.jar commons-codec-1.4.jar  * @author tianjun**/public class PostTest{public static void main(String[] args){// (1)構造HttpClient的例項
HttpClient httpClient = new HttpClient();// (2)建立POST方法的例項PostMethod postMethod = new PostMethod("http://localhost:8080/b/test1.do");// GetMethod getMethod = new// GetMethod("http://localhost:8080/b/test1.do");// (3)設定http request頭List<Header> headers = new ArrayList<Header>();headers.add(new Header("tianjun_key"
,"tianjun_value"));httpClient.getHostConfiguration().getParams().setParameter("http.default-headers", headers);// 使用系統提供的預設的恢復策略postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());// getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,// new DefaultHttpMethodRetryHandler());try{// (4)執行postMethodint statusCode = httpClient.executeMethod(postMethod);if (statusCode != HttpStatus.SC_OK){System.err.println("Method failed:"+ postMethod.getStatusLine());}// (5)讀取response頭資訊Header headerResponse = postMethod.getResponseHeader("response_key");String headerStr = headerResponse.getValue();// (6)讀取內容byte[] responseBody = postMethod.getResponseBody();// (7) 處理內容System.out.println(headerStr);System.out.println(new String(responseBody));} catch (HttpException e){// 發生致命的異常,可能是協議不對或者返回的內容有問題System.out.println("Please check your provided http address!");e.printStackTrace();} catch (IOException e){e.printStackTrace();} catch (Exception e){e.printStackTrace();} finally{// 釋放連線postMethod.releaseConnection();}}}