import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.URIException;
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.util.URIUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* HTTP工具箱
*
* @author leizhimin 2009-6-19 16:36:18
*/
public final class HttpTookit {
private static Log log = LogFactory.getLog(HttpTookit.class);
/**
* 执行一个HTTP GET请求,返回请求响应的HTML
*
* @param url 请求的URL地址
* @param queryString 请求的查询参数,可以为null
* @return 返回请求响应的HTML
*/
public static String doGet(String url, String queryString) {
String response = null;
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(url);
try {
if (StringUtils.isNotBlank(queryString))
method.setQueryString(URIUtil.encodeQuery(queryString));
client.executeMethod(method);
if (method.getStatusCode() == HttpStatus.SC_OK) {
response = method.getResponseBodyAsString();
}
} catch (URIException e) {
log.error("执行HTTP Get请求时,编码查询字符串“" + queryString + "”发生异常!", e);
} catch (IOException e) {
log.error("执行HTTP Get请求" + url + "时,发生异常!", e);
} finally {
method.releaseConnection();
}
return response;
}
/**
* 执行一个HTTP POST请求,返回请求响应的HTML
*
* @param url 请求的URL地址
* @param params 请求的查询参数,可以为null
* @return 返回请求响应的HTML
*/
public static String doPost(String url, Map<String, String> params) {
String response = null;
HttpClient client = new HttpClient();
HttpMethod method = new PostMethod(url);
for (Iterator it = params.entrySet().iterator(); it.hasNext();) {
}
//设置Http Post数据
if (params != null) {
HttpMethodParams p = new HttpMethodParams();
for (Map.Entry<String, String> entry : params.entrySet()) {
p.setParameter(entry.getKey(), entry.getValue());
}
method.setParams(p);
}
try {
client.executeMethod(method);
if (method.getStatusCode() == HttpStatus.SC_OK) {
response = method.getResponseBodyAsString();
}
} catch (IOException e) {
log.error("执行HTTP Post请求" + url + "时,发生异常!", e);
} finally {
method.releaseConnection();
}
return response;
}
public static void main(String[] args) {
String x = doPost("http://lavasoft.blog.51cto.com/62575/64994", new HashMap());
System.out.println(x);
}
}
一般网络会给我们提供许多数据接口,我们的一些信息并不是我们本系统提供而是第三方给我们提供的,他们通常会给我们一个提供数据源的接口,访问这个接口可以获取相应的数据用于我们自己的应用中(WebService和现如今的json/xml通过http信息的传输模式都是如此)。
httpClient是一款优秀的基于https协议的网络发送http请求并获取相应的api,下面就来探讨一下如何使用httpClient进行get和post两种方式的http通信。
我们接下来要做的,就是提供一个数据接口,此数据接口提供整数计算服务,传入两个参数(要求是整数)和一个运算符参数,就可以得到最终的运算结果。如,传递param1=1,param2=2,operator='+',那么接口就会返回result:3。
开发环境:MyEclipse8.5,JDK1.7,Tomcat6.0 httpClient3.0
下面我们开始编写这个Servlet,具体实现就是获取请求中的三个参数(两个运算值一个运算符号),然后进行计算然后返回结果 (网页直接调用和后台使用 httpclient测试):
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;
public class TestHTTPServer extends HttpServlet {
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);
String operator=request.getParameter("operator");
out.println(operator.equals(" ")?"operator=+":"operator="+operator);
if(param1 == null || param1.equals("") || param1.length()<=0){
out.println("http call failed,参数param1不能为空,程序退出");
}else if(param2 == null || param2.equals("") || param2.length()<=0){
out.println("http call failed,参数param2不能为空,程序退出");
}else if(operator == null || operator.equals("") || operator.length()<=0){
out.println("http call failed,参数operator不能为空,程序退出");
}else{
out.println("---http call success---");
}
int n=Integer.parseInt(param1);
int m=Integer.parseInt(param2);
if(operator.equals(" ")){
out.println("result:"+(n+m));
}else if(operator.equals("-")){
out.println("result:"+(n-m));
}else if(operator.equals("*")){
out.println("result:"+(n*m));
}else if(operator.equals("/")){
out.println("result:"+(n/m));
}else{
out.println("---unknow error---");
}
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
注意:“+”号通过URL传递到后台会被默认转义为空格“ ”,所以这里验证“+”号是用的是空格。
将Servlet部署到web服务器中(略)
此时,在浏览器访问我们的服务,参数分别输入6、2和*,得到最终结果是6乘以2为12:
其他方法测试(略)
好,我们的服务接口已经提供完毕了,接下来我们使用httpClient的get和post对这个http接口进行调用。
我们使用httpClinet分别编写了使用get与post方式进行http数据传输的方法,在main主方法中,对其进行了测试,分别使用get和post请求获取数据接口服务计算的结果:
package httpcall;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
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.logging.Log;
import org.apache.commons.logging.LogFactory;
public class HttpClientUtil {
private static final Log log=LogFactory.getLog(HttpClientUtil.class);
/**
* get 方式
* @param param1
* @param param2
* @param opt
* @return String
* */
public static String getHttp(String param1,String param2,String opt){
String responseMsg="";
//1.构造HttpClient的实例
HttpClient httpClient=new HttpClient();
//用于测试的http接口的url
String url="http://localhost:8081/HttpTest/httpServer?param1="
+param1+"¶m2="+param2+"&operator="+opt;
//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 (Exception e) {
e.printStackTrace();
}finally{
//6.释放连接
getMethod.releaseConnection();
}
return responseMsg;
}
/**
* post 方式
* @param param1
* @param param2
* @param opt
* @return String
* */
public static String postHttp(String param1,String param2,String opt){
String responseMsg="";
//1.构造HttpClient的实例
HttpClient httpClient=new HttpClient();
httpClient.getParams().setContentCharset("GBK");
String url="http://localhost:8081/HttpTest/httpServer";
//2.构造PostMethodd的实例
PostMethod postMethod=new PostMethod(url);
//3.把参数值放入到PostMethod对象中
postMethod.addParameter("param1",param1);
postMethod.addParameter("param2",param2);
postMethod.addParameter("operator",opt);
try {
//4.执行postMethod,调用http接口
httpClient.executeMethod(postMethod);//200
//5.读取内容
responseMsg=postMethod.getResponseBodyAsString().trim();
//6.处理返回的内容
log.info(responseMsg);
} catch (Exception e) {
e.printStackTrace();
}finally{
//7.释放连接
postMethod.releaseConnection();
}
return responseMsg;
}
/**
* 测试的main方法
* @param args
* */
public static void main(String[] args) {
String param1="6";
String param2="2";
String opt="*";
System.out.println("get方式调用http接口\n"+getHttp(param1,param2,opt));
System.out.println("post方式调用http接口\n"+postHttp(param1,param2,opt));
}
}
运行结果:
证明我们成功使用httpClient访问了第三方数据接口,并获取了相应的数据。
http://blog.csdn.net/acmman/article/details/51839367
其他参考资料
Java模拟HTTP的Get和Post请求
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.URIException;
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.util.URIUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* HTTP工具箱
*
* @author leizhimin 2009-6-19 16:36:18
*/
public final class HttpTookit {
private static Log log = LogFactory.getLog(HttpTookit.class);
/**
* 执行一个HTTP GET请求,返回请求响应的HTML
*
* @param url 请求的URL地址
* @param queryString 请求的查询参数,可以为null
* @return 返回请求响应的HTML
*/
public static String doGet(String url, String queryString) {
String response = null;
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(url);
try {
if (StringUtils.isNotBlank(queryString))
method.setQueryString(URIUtil.encodeQuery(queryString));
client.executeMethod(method);
if (method.getStatusCode() == HttpStatus.SC_OK) {
response = method.getResponseBodyAsString();
}
} catch (URIException e) {
log.error("执行HTTP Get请求时,编码查询字符串“" + queryString + "”发生异常!", e);
} catch (IOException e) {
log.error("执行HTTP Get请求" + url + "时,发生异常!", e);
} finally {
method.releaseConnection();
}
return response;
}
/**
* 执行一个HTTP POST请求,返回请求响应的HTML
*
* @param url 请求的URL地址
* @param params 请求的查询参数,可以为null
* @return 返回请求响应的HTML
*/
public static String doPost(String url, Map<String, String> params) {
String response = null;
HttpClient client = new HttpClient();
HttpMethod method = new PostMethod(url);
for (Iterator it = params.entrySet().iterator(); it.hasNext();) {
}
//设置Http Post数据
if (params != null) {
HttpMethodParams p = new HttpMethodParams();
for (Map.Entry<String, String> entry : params.entrySet()) {
p.setParameter(entry.getKey(), entry.getValue());
}
method.setParams(p);
}
try {
client.executeMethod(method);
if (method.getStatusCode() == HttpStatus.SC_OK) {
response = method.getResponseBodyAsString();
}
} catch (IOException e) {
log.error("执行HTTP Post请求" + url + "时,发生异常!", e);
} finally {
method.releaseConnection();
}
return response;
}
public static void main(String[] args) {
String x = doPost("http://lavasoft.blog.51cto.com/62575/64994", new HashMap());
System.out.println(x);
}
}
运行后打印结果如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>Java中使用正则表达式校验字符串 - 熔 岩 - 51CTO技术博客</title>
<meta name="description" content="Java中使用正则表达式校验字符串正则表达式是某一位伟大的数学家发明的,现在已经形成了一个ISO标准,这个标准和编程语言没有关系。至于具体谁发明的,怎么发明的,我也忘记了:)。 正则表达式简单理解就是..">
<meta name="keywords" content="Java中使用正则表达式校验字符串">
<meta http-equiv="Cache-Control" content="private">
<base href="http://lavasoft.blog.51cto.com/"></base>
<script src="/js/def.js"></script>
<SCRIPT language=javascript src="http://blog.51cto.com/js/message.js" type=text/javascript></SCRIPT>
<SCRIPT language=javascript src="http://blog.51cto.com/js/user_comment.js" type=text/javascript></SCRIPT>
<SCRIPT language=javascript src="http://blog.51cto.com/js/base2.js" type=text/javascript></SCRIPT>
<SCRIPT language=javascript src="http://blog.51cto.com/js/dialog_utf8.js" type=text/javascript></SCRIPT>
<link href="/css/skin/2.css" rel="stylesheet" type="text/css">
<link href="/css/group/group.css" rel="stylesheet" type="text/css">
<link rel="alternate" href="../rss.php?uid=62575" type="application/rss+xml" title="RSS 2.0">
<link rel="edituri" type="application/rsd+xml" title="rsd" href="xmlrpc.php?rsd=1" />
<script>
var myid = "";
function add_flink(){
if(myid){
var url='/mod/edit_flink.php?type=addflink&uid=62575&flink=http://lavasoft.blog.51cto.com';
var ajax = InitAjax1();
ajax.open("GET", url, true);
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
if(ajax.responseText==""){
alert("添加成功。");
}
if(ajax.responseText=="1"){
alert("链接指向自己。");
}
if(ajax.responseText=="2"){
alert("友情链接已存在。")
}
}
}
ajax.send(null);
}else{
var refurlk = "http://lavasoft.blog.51cto.com/62575/64994";
commentSubmit("",refurlk);
return false;
}
}
function sendmessage(){
var refurlk = "http://lavasoft.blog.51cto.com/62575/64994";
if(myid){
return true;
}else{
commentSubmit("",refurlk);
return false;
}
}
function copylink(ourl){
if(!ourl){
var clipBoardContent = "http://lavasoft.blog.51cto.com";
}else{
var clipBoardContent = ourl;
}
window.clipboardData.setData("Text",clipBoardContent);
alert("复制成功!");
return false;
}
function correctPNG() {
if (document.getElementById('blog_touxian'))
{
var img = document.getElementById('blog_touxian');
var imgName = img.src.toUpperCase()
var imgID = (img.id) ? "id='" + img.id + "' " : ""
var imgClass = (img.className) ? "class='" + img.className + "' " : ""
var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
var imgStyle = "display:inline-block;" + img.style.cssText
if (img.align == "left") imgStyle = "float:left;" + imgStyle
if (img.align == "right") imgStyle = "float:right;" + imgStyle
if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
var strNewHTML = "<span " + imgID + imgClass + imgTitle
+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
+ "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" ;
img.outerHTML = strNewHTML;
}
}
//window.attachEvent(" correctPNG);
window.
</script>
<style type="text/css">
#layout_0{
width:;
float:left;
}
#layout_1{
width:;
float:left;
}
#layout_3{
width:;
float:left;
}
.albumalert{
width:250px;
height:150px;
background:#fff;
border:1px solid #777;
}
.alerttitle{
text-align:left;
color:#000;
padding:6px;
background-image:url("http://img1.51cto.com/images/quickwindow.jpg");
background-repeat:repeat-x;
font-size:14px;
height:22px;
}
.alertcentent{
line-height:30px;
}
.alertcentent p{
color:#000;
}
以上代码省略了N多行。
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import com.verisign.uuid.UUID;
/**
* 向一个飞信zhapian网站自动提交垃圾信息的程序,用空可以运行一下。
* @author wangpeng
*
*/
public class AutoSubmit {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
for(int i=0; i < 100000; i++){
post(i);
}
}
private static void post(int i) throws Exception{
String s = UUID.generate().toString();
String s1 = s.substring(0,2);
s = s1+ s.substring(s.length() - 3, s.length());
URL url = new URL("http://yfs88.sv10.sgedns.cn/yy/e/qq22.asp");// 提交地址
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);// 打开写入属性
httpURLConnection.setDoInput(true);// 打开读取属性
httpURLConnection.setRequestMethod("POST");// 设置提交方法
httpURLConnection.setConnectTimeout(50000);// 连接超时时间
httpURLConnection.setReadTimeout(50000);
httpURLConnection.connect();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(httpURLConnection.getOutputStream(), "GBK"));
out.write("name=" + s + i + //用户名不能重复
"&password=748" +
"&sex=ri你很行" +
"&oicq=748748" +
"&icq=748748" +
"&msn=caonima" +
"&shengri=再不关门滚蛋,就把你们全关起来" +
"&home=已经盯上你们了");//要post的数据,多个以&符号分割
out.flush();
out.close();
//读取post之后的返回值
// BufferedReader in = new BufferedReader(new InputStreamReader((InputStream) httpURLConnection.getInputStream()));
// String line = null;
// StringBuilder sb = new StringBuilder();
// while ((line = in.readLine()) != null) {
// sb.append(line);
// }
// in.close();
// System.out.println("client:" + sb.toString());
httpURLConnection.disconnect();//断开连接
//
System.out.println("client post ok:" + i);
}
}
上面程序师通过JDK的原生API实现的,很不错的一个程序。