get/post方式調用http接口 – JAVA編程語言程序開發技術文章

本節摘要:本節主要分別介紹如何用get方式、post方式向http接口發送數據。

preparation
1. 項目環境如下:

myeclipse6.5 、tomcat5.0、system:xp、JDK:開發1.5,編譯1.4

為瞭方便,在原來的web項目UpDown中新建瞭一個httpcall包,用來保存http接口和調用的客戶端。

 5

 

2.準備需要的jar包
* commons-httpclient-3.0.jar
* commons-logging.jar
* commons-codec-1.3.jar
 
3.class&method
HttpClient:
GetMethod:
PostMethod:
 
start
接口寫瞭一個servlet來接收客戶端get/post的請求
web.xml需要加入以下配置:
<!– 模擬HTTP的調用,寫的一個http接口 –>
    <servlet>
        <servlet-name>TestHTTPServer</servlet-name>
        <servlet-class>httpcall.TestHTTPServer</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>TestHTTPServer</servlet-name>
        <url-pattern>/httpServer</url-pattern>
    </servlet-mapping>
 
TestHTTPServer.java的代碼如下:
 
  TestHTTPServer
 1 package httpcall;
 2
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 import javax.servlet.ServletException;
 6 import javax.servlet.http.HttpServlet;
 7 import javax.servlet.http.HttpServletRequest;
 8 import javax.servlet.http.HttpServletResponse;
 9
10 /**
11  *Module:       TestHTTPServer.java
12  *Description:  為瞭驗證http接口的調用,編寫瞭一個模擬的http接口
13  *Company:     
14  *Author:       ptp
15  *Date:         Feb 22, 2012
16  */
17
18 public class TestHTTPServer  extends HttpServlet{
19    
20     private static final long serialVersionUID = 1L;
21
22     public void doGet(HttpServletRequest request, HttpServletResponse response)
23             throws ServletException, IOException {
24         response.setCharacterEncoding("gbk");
25
26         PrintWriter out = response.getWriter();
27         String param1 = request.getParameter("param1");
28         out.println("param1=" + param1);
29         String param2 = request.getParameter("param2");
30         out.println("param2=" + param2);
31         if (param1 == null || "".equals("param1") || param1.length() <= 0) {
32             out.println("http call failed,參數param1不能為空,程序退出");
33         } else if (param2 == null || "".equals("param2")
34                 || param2.length() <= 0) {
35             out.println("http call failed,參數param2不能為空,程序退出");
36         } else {
37             out.println("—http call success—");
38         }
39         out.close();
40     }
41
42     public void doPost(HttpServletRequest request, HttpServletResponse response)
43             throws ServletException, IOException {
44         this.doGet(request, response);
45     }
46 }

 
HttpClientUtil.java的代碼如下:
  HttpClientUtil
  1 package httpcall;
  2
  3 import java.io.IOException;
  4 import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
  5 //import org.apache.commons.httpclient.Header;
  6 import org.apache.commons.httpclient.HttpClient;
  7 import org.apache.commons.httpclient.HttpException;
  8 //import org.apache.commons.httpclient.HttpStatus;
  9 import org.apache.commons.httpclient.methods.GetMethod;
 10 import org.apache.commons.httpclient.methods.PostMethod;
 11 import org.apache.commons.httpclient.params.HttpMethodParams;
 12 //import org.apache.commons.httpclient.NameValuePair;
 13 import org.apache.commons.logging.Log;
 14 import org.apache.commons.logging.LogFactory;
 15
 16 /**
 17  *
 18  *Module:       HttpClientUtil.java
 19  *Description:  以get/post的方式發送數據到指定的http接口—利用httpclient.jar包—HTTP接口的調用
 20  *Company:     
 21  *Author:       ptp
 22  *Date:         Feb 22, 2012
 23  */
 24
 25 public class HttpClientUtil {
 26    
 27     private static final Log log = LogFactory
 28     .getLog(HttpClientUtil.class);
 29
 30     /**
 31      * get方式
 32      * @param param1
 33      * @param param2
 34      * @return
 35 */
 36     public static String getHttp(String param1,String param2){
 37         String responseMsg = "";
 38
 39         // 1.構造HttpClient的實例
 40         HttpClient httpClient = new HttpClient();
 41
 42         // 用於測試的http接口的url
 43         String url="http://localhost:8080/UpDown/httpServer?param1="+param1+"&param2="+param2;
 44
 45         // 2.創建GetMethod的實例
 46         GetMethod getMethod = new GetMethod(url);
 47
 48         // 使用系統系統的默認的恢復策略
 49         getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
 50                 new DefaultHttpMethodRetryHandler());
 51        
 52         try {
 53             //3.執行getMethod,調用http接口
 54             httpClient.executeMethod(getMethod);
 55
 56             //4.讀取內容
 57             byte[] responseBody = getMethod.getResponseBody();
 58            
 59             //5.處理返回的內容
 60             responseMsg = new String(responseBody);
 61             log.info(responseMsg);
 62            
 63         } catch (HttpException e) {
 64             e.printStackTrace();
 65         } catch (IOException e) {
 66             e.printStackTrace();
 67         }finally{
 68             //6.釋放連接
 69             getMethod.releaseConnection();
 70         }
 71         return responseMsg;
 72     }
 73
 74     /**
 75      * post方式
 76      * @param param1
 77      * @param param2
 78      * @return
 79 */
 80     public static String postHttp(String param1,String param2) {
 81         String responseMsg = "";
 82        
 83         //1.構造HttpClient的實例
 84         HttpClient httpClient=new HttpClient();
 85        
 86         httpClient.getParams().setContentCharset("GBK");
 87        
 88         String url="http://localhost:8080/UpDown/httpServer";
 89        
 90         //2.構造PostMethod的實例
 91         PostMethod postMethod=new PostMethod(url);
 92        
 93         //3.把參數值放入到PostMethod對象中
 94 //方式1:
 95 /*        NameValuePair[] data = { new NameValuePair("param1", param1),
 96                 new NameValuePair("param2", param2) };
 97         postMethod.setRequestBody(data);*/
 98        
 99         //方式2:   
100         postMethod.addParameter("param1", param1);
101         postMethod.addParameter("param2", param2);
102        
103        
104         try {
105             // 4.執行postMethod,調用http接口
106             httpClient.executeMethod(postMethod);//200
107            
108 //5.讀取內容
109             responseMsg = postMethod.getResponseBodyAsString().trim();
110             log.info(responseMsg);
111            
112             //6.處理返回的內容
113
114         } catch (HttpException e) {
115             e.printStackTrace();
116         } catch (IOException e) {
117             e.printStackTrace();
118         } finally {
119             //7.釋放連接
120             postMethod.releaseConnection();
121         }
122         return responseMsg;
123     }
124
125     /**
126      * 測試的main方法
127      * @param args
128 */
129     public static void main(String[] args) {
130    
131         String param1="111";
132         String param2="222";
133         //get
134 //        System.out.println("get方式調用http接口\n"+getHttp(param1, param2));
135        
136 //post
137         System.out.println("post方式調用http接口\n"+postHttp(param1,param2));
138     }
139 }

 
result
在HttpClientUtil運行main方法,分別運行以下幾種情況:
1.get方式
設置
String param1="111";
String param2="222";
運行get方式,截圖如下:

 1

 

設置

String param1="111";
String param2="";

運行get方式,截圖如下:

 2

 

2.post方式

設置

String param1="111";
String param2="222";

運行post方式,截圖如下:

 3

 

設置

String param1="111";
String param2="";

運行post方式,截圖如下:

 4

 

通過get和post方式調用http接口,總結如下:

* get方式調用http接口的步驟:
* 1.構造HttpClient實例
* 2.構造GetMethod實例
* 3.執行getMethod,調用http接口
* 4.讀取內容
* 5.處理返回的內容
* 6.釋放連接
*
* post方式調用http接口的步驟:
* 1.構造HttpClient實例
* 2.構造PostMethod實例
* 3.把參數值放入到PostMethod對象中
*   方式1:利用NameValuePair類
*   方式2:直接用PostMethod實例對象的addParameter方法
* 4.執行postMethod,調用http接口
* 5.讀取內容
* 6.處理返回的內容
* 7.釋放連接

 

摘自 月月鳥0820

發佈留言