本节摘要:本节主要分别介绍如何用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需要加入以下配置:
<!-- 模拟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
package httpcall;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*Module: TestHTTPServer.java
*Description: 为了验证http接口的调用,编写了一个模拟的http接口
*Company:
*Author: ptp
*Date: Feb 22, 2012
*/
public class TestHTTPServer extends HttpServlet{
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("gbk");
PrintWriter out = response.getWriter();
String param1 = request.getParameter("param1");
out.println("param1=" + param1);
String param2 = request.getParameter("param2");
out.println("param2=" + param2);
if (param1 == null || "".equals("param1") || param1.length() <= 0) {
out.println("http call failed,参数param1不能为空,程序退出");
} else if (param2 == null || "".equals("param2")
|| param2.length() <= 0) {
out.println("http call failed,参数param2不能为空,程序退出");
} else {
out.println("---http call success---");
}
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
HttpClientUtil.java的代码如下:
HttpClientUtil
package httpcall;
import java.io.IOException;
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.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
//import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
*Module: HttpClientUtil.java
*Description: 以get/post的方式发送数据到指定的http接口---利用httpclient.jar包---HTTP接口的调用
*Company:
*Author: ptp
*Date: Feb 22, 2012
*/
public class HttpClientUtil {
private static final Log log = LogFactory
.getLog(HttpClientUtil.class);
/**
* get方式
* @param param1
* @param param2
* @return
*/
public static String getHttp(String param1,String param2){
String responseMsg = "";
// 1.构造HttpClient的实例
HttpClient httpClient = new HttpClient();
// 用于测试的http接口的url
String url="http://localhost:8080/UpDown/httpServer?param1="+param1+"¶m2="+param2;
// 2.创建GetMethod的实例
GetMethod getMethod = new GetMethod(url);
// 使用系统系统的默认的恢复策略
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler());
try {
//3.执行getMethod,调用http接口
httpClient.executeMethod(getMethod);
//4.读取内容
byte[] responseBody = getMethod.getResponseBody();
//5.处理返回的内容
responseMsg = new String(responseBody);
log.info(responseMsg);
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
//6.释放连接
getMethod.releaseConnection();
}
return responseMsg;
}
/**
* post方式
* @param param1
* @param param2
* @return
*/
public static String postHttp(String param1,String param2) {
String responseMsg = "";
//1.构造HttpClient的实例
HttpClient httpClient=new HttpClient();
httpClient.getParams().setContentCharset("GBK");
String url="http://localhost:8080/UpDown/httpServer";
//2.构造PostMethod的实例
PostMethod postMethod=new PostMethod(url);
//3.把参数值放入到PostMethod对象中
//方式1:
/* NameValuePair[] data = { new NameValuePair("param1", param1),
new NameValuePair("param2", param2) };
postMethod.setRequestBody(data);*/
//方式2:
postMethod.addParameter("param1", param1);
postMethod.addParameter("param2", param2);
try {
// 4.执行postMethod,调用http接口
httpClient.executeMethod(postMethod);//200
//5.读取内容
responseMsg = postMethod.getResponseBodyAsString().trim();
log.info(responseMsg);
//6.处理返回的内容
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//7.释放连接
postMethod.releaseConnection();
}
return responseMsg;
}
/**
* 测试的main方法
* @param args
*/
public static void main(String[] args) {
String param1="111";
String param2="222";
//get
// System.out.println("get方式调用http接口\n"+getHttp(param1, param2));
//post
System.out.println("post方式调用http接口\n"+postHttp(param1,param2));
}
}
result
在HttpClientUtil运行main方法,分别运行以下几种情况:
1.get方式
设置
String param1="111";
String param2="222";
运行get方式,截图如下:
设置
String param1="111";
String param2="";
运行get方式,截图如下:
2.post方式
设置
String param1="111";
String param2="222";
运行post方式,截图如下:
设置
String param1="111";
String param2="";
运行post方式,截图如下:
通过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.释放连接