如何用get方post方式向http接口发送数据
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
本节摘要:本节主要分别介绍如何用get方式、post方式向http接口发送数据。
preparation
1. 项目环境如下:
myeclipse6.5 、tomcat5.0、system:xp、JDK:开发1.5,编译1.4
为了方便,在原来的web项目UpDown中新建了一个httpcall包,用来保存http接口和调用的客户端。
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需要加入以下配置:
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;
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;
3 import java.io.IOException;
4 import mons.httpclient.DefaultHttpMethodRetryHandler;
5 //import mons.httpclient.Header;
6 import mons.httpclient.HttpClient;
7 import mons.httpclient.HttpException;
8 //import mons.httpclient.HttpStatus;
9 import mons.httpclient.methods.GetMethod;
10 import mons.httpclient.methods.PostMethod;
11 import mons.httpclient.params.HttpMethodParams;
12 //import ValuePair;
13 import mons.logging.Log;
14 import mons.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