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, Mapparams) { 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 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, Mapparams) { 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 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); } }
运行后打印结果如下:
Java中使用正则表达式校验字符串 - 熔 岩 - 51CTO技术博客