get/post方式调用http接口

ぐ巨炮叔叔 提交于 2019-11-29 10:18:12

本节摘要:本节主要分别介绍如何用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.java12  *Description:  为了验证http接口的调用,编写了一个模拟的http接口13  *Company:      14  *Author:       ptp15  *Date:         Feb 22, 201216  */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);//200107             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 args128 */129     public static void main(String[] args) {130     131         String param1="111";132         String param2="222";133         //get134 //        System.out.println("get方式调用http接口\n"+getHttp(param1, param2));135         136 //post137         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.释放连接

本节摘要:本节主要分别介绍如何用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.java12  *Description:  为了验证http接口的调用,编写了一个模拟的http接口13  *Company:      14  *Author:       ptp15  *Date:         Feb 22, 201216  */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);//200107             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 args128 */129     public static void main(String[] args) {130     131         String param1="111";132         String param2="222";133         //get134 //        System.out.println("get方式调用http接口\n"+getHttp(param1, param2));135         136 //post137         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.释放连接

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!