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)執行postMethod int 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(); } } }

再分享一下我老師大神的人工智慧教程吧。零基礎!通俗易懂!風趣幽默!還帶黃段子!希望你也加入到我們人工智慧的隊伍中來!https://www.cnblogs.com/captainbed