最近做在线支付时遇到需要以后台方式访问URL并获取其返回的数据的问题,在网络上g了一把,发现在常用的还是Apache的HttpClient。因为以经常要用到的原故,因此我对其进行了一些简单的封装,在此将代码贴一来,希望对有需要的朋友有所帮助,呵呵...

HttpUtils.java中有两个公共的静态方法,一个是URLPost,另一个是URLGet,一目了然,前者是提供POST方式提交数据的,后者是提供GET方式提交数据的。其中所需要传送的数据以Map的方式传入,剩下的工作就交给我这个HttpUtils吧!当然如果Http服务器端对所提交的数据的编码有要求的话,也没问题,你可以传入UTF-8或者GBK,当然大家还可自行增加。

下面是源代码,如果使用中有什么问题,欢迎大家提出。

  1. import java.io.IOException;
  2. import java.io.UnsupportedEncodingException;
  3. import java.net.URLEncoder;
  4. import java.util.Iterator;
  5. import java.util.Map;
  6. import java.util.Set;
  7. import org.apache.commons.httpclient.HttpClient;
  8. import org.apache.commons.httpclient.HttpException;
  9. import org.apache.commons.httpclient.HttpStatus;
  10. import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
  11. import org.apache.commons.httpclient.methods.GetMethod;
  12. import org.apache.commons.httpclient.methods.PostMethod;
  13. import org.apache.commons.logging.Log;
  14. import org.apache.commons.logging.LogFactory;
  15. /**
  16. * HTTP工具类
  17. *
  18. * @author lixiangyang
  19. *
  20. */
  21. public class HttpUtils {
  22. private static Log log = LogFactory.getLog(HttpUtils.class);
  23. /**
  24. * 定义编码格式 UTF-8
  25. */
  26. public static final String URL_PARAM_DECODECHARSET_UTF8 = "UTF-8";
  27. /**
  28. * 定义编码格式 GBK
  29. */
  30. public static final String URL_PARAM_DECODECHARSET_GBK = "GBK";
  31. private static final String URL_PARAM_CONNECT_FLAG = "&";
  32. private static final String EMPTY = "";
  33. private static MultiThreadedHttpConnectionManager connectionManager = null;
  34. private static int connectionTimeOut = 25000;
  35. private static int socketTimeOut = 25000;
  36. private static int maxConnectionPerHost = 20;
  37. private static int maxTotalConnections = 20;
  38. private static HttpClient client;
  39. static{
  40. connectionManager = new MultiThreadedHttpConnectionManager();
  41. connectionManager.getParams().setConnectionTimeout(connectionTimeOut);
  42. connectionManager.getParams().setSoTimeout(socketTimeOut);
  43. connectionManager.getParams().setDefaultMaxConnectionsPerHost(maxConnectionPerHost);
  44. connectionManager.getParams().setMaxTotalConnections(maxTotalConnections);
  45. client = new HttpClient(connectionManager);
  46. }
  47. /**
  48. * POST方式提交数据
  49. * @param url
  50. *          待请求的URL
  51. * @param params
  52. *          要提交的数据
  53. * @param enc
  54. *          编码
  55. * @return
  56. *          响应结果
  57. * @throws IOException
  58. *          IO异常
  59. */
  60. public static String URLPost(String url, Map<String, String> params, String enc){
  61. String response = EMPTY;
  62. PostMethod postMethod = null;
  63. try {
  64. postMethod = new PostMethod(url);
  65. postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + enc);
  66. //将表单的值放入postMethod中
  67. Set<String> keySet = params.keySet();
  68. for(String key : keySet){
  69. String value = params.get(key);
  70. postMethod.addParameter(key, value);
  71. }
  72. //执行postMethod
  73. int statusCode = client.executeMethod(postMethod);
  74. if(statusCode == HttpStatus.SC_OK) {
  75. response = postMethod.getResponseBodyAsString();
  76. }else{
  77. log.error("响应状态码 = " + postMethod.getStatusCode());
  78. }
  79. }catch(HttpException e){
  80. log.error("发生致命的异常,可能是协议不对或者返回的内容有问题", e);
  81. e.printStackTrace();
  82. }catch(IOException e){
  83. log.error("发生网络异常", e);
  84. e.printStackTrace();
  85. }finally{
  86. if(postMethod != null){
  87. postMethod.releaseConnection();
  88. postMethod = null;
  89. }
  90. }
  91. return response;
  92. }
  93. /**
  94. * GET方式提交数据
  95. * @param url
  96. *          待请求的URL
  97. * @param params
  98. *          要提交的数据
  99. * @param enc
  100. *          编码
  101. * @return
  102. *          响应结果
  103. * @throws IOException
  104. *          IO异常
  105. */
  106. public static String URLGet(String url, Map<String, String> params, String enc){
  107. String response = EMPTY;
  108. GetMethod getMethod = null;
  109. StringBuffer strtTotalURL = new StringBuffer(EMPTY);
  110. if(strtTotalURL.indexOf("?") == -1) {
  111. strtTotalURL.append(url).append("?").append(getUrl(params, enc));
  112. } else {
  113. strtTotalURL.append(url).append("&").append(getUrl(params, enc));
  114. }
  115. log.debug("GET请求URL = \n" + strtTotalURL.toString());
  116. try {
  117. getMethod = new GetMethod(strtTotalURL.toString());
  118. getMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + enc);
  119. //执行getMethod
  120. int statusCode = client.executeMethod(getMethod);
  121. if(statusCode == HttpStatus.SC_OK) {
  122. response = getMethod.getResponseBodyAsString();
  123. }else{
  124. log.debug("响应状态码 = " + getMethod.getStatusCode());
  125. }
  126. }catch(HttpException e){
  127. log.error("发生致命的异常,可能是协议不对或者返回的内容有问题", e);
  128. e.printStackTrace();
  129. }catch(IOException e){
  130. log.error("发生网络异常", e);
  131. e.printStackTrace();
  132. }finally{
  133. if(getMethod != null){
  134. getMethod.releaseConnection();
  135. getMethod = null;
  136. }
  137. }
  138. return response;
  139. }
  140. /**
  141. * 据Map生成URL字符串
  142. * @param map
  143. *          Map
  144. * @param valueEnc
  145. *          URL编码
  146. * @return
  147. *          URL
  148. */
  149. private static String getUrl(Map<String, String> map, String valueEnc) {
  150. if (null == map || map.keySet().size() == 0) {
  151. return (EMPTY);
  152. }
  153. StringBuffer url = new StringBuffer();
  154. Set<String> keys = map.keySet();
  155. for (Iterator<String> it = keys.iterator(); it.hasNext();) {
  156. String key = it.next();
  157. if (map.containsKey(key)) {
  158. String val = map.get(key);
  159. String str = val != null ? val : EMPTY;
  160. try {
  161. str = URLEncoder.encode(str, valueEnc);
  162. } catch (UnsupportedEncodingException e) {
  163. e.printStackTrace();
  164. }
  165. url.append(key).append("=").append(str).append(URL_PARAM_CONNECT_FLAG);
  166. }
  167. }
  168. String strURL = EMPTY;
  169. strURL = url.toString();
  170. if (URL_PARAM_CONNECT_FLAG.equals(EMPTY + strURL.charAt(strURL.length() - 1))) {
  171. strURL = strURL.substring(0, strURL.length() - 1);
  172. }
  173. return (strURL);
  174. }
  175. }

基于HttpClient的HttpUtils(后台访问URL)的更多相关文章

  1. nginx针对某个url限制ip访问,常用于后台访问限制【转】

    假如我的站点后台地址为: http://www.abc.net/admin.php 那么我想限制只有个别ip可以访问后台,那么需要在配置文件中增加: location ~ .*admin.* { al ...

  2. Spring RestTemplate: 比httpClient更优雅的Restful URL访问, java HttpPost with header

    { "Author": "tomcat and jerry", "url":"http://www.cnblogs.com/tom ...

  3. 基于shiro+jwt的真正rest url权限管理,前后端分离

    代码地址如下:http://www.demodashi.com/demo/13277.html bootshiro & usthe bootshiro是基于springboot+shiro+j ...

  4. 利用javascript Location访问Url,重定向,刷新页面

    网上转来了, 方便以后查询参考 本文介绍怎么使用javascript Location对象读和修改Url.怎么重载或刷新页面.javascript提供了许多方法访问,修改当前用户在浏览器中访问的url ...

  5. 基于SpringBoot的项目管理后台

    代码地址如下:http://www.demodashi.com/demo/13943.html 一.项目简介 在使用本项目之前,需要对SpringBoot,freemaker,layui,flyway ...

  6. 基于WCF 的远程数据库服务访问技术

    原文出处:http://www.lw80.cn/shuji/jsjlw/13588Htm.Htm摘要:本文介绍了使用WCF 建立和运行面向服务(SOA)的数据库服务的系统结构和技术要素,分析了WCF ...

  7. SpringCloud-Config通过Java访问URL对敏感词加密解密

    特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过.如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/ ...

  8. 基于vue模块化开发后台系统——准备工作

    文章目录如下:项目效果预览地址项目开源代码基于vue模块化开发后台系统--准备工作基于vue模块化开发后台系统--构建项目基于vue模块化开发后台系统--权限控制 前言 本文章是以学习为主,练习一下v ...

  9. Django项目:CRM(客户关系管理系统)--84--74PerfectCRM实现CRM权限和权限组限制访问URL

    #models.py # ————————01PerfectCRM基本配置ADMIN———————— from django.db import models # Create your models ...

随机推荐

  1. file-loader 与 url-loader 的区别

    url-loader是对file-loader的一个封装,比如webpack中对图片的加载器配置 {test: /\.(png|jpg)$/, loader: 'url-loader?limit=81 ...

  2. 自定义django model form、admin action

    https://www.cnblogs.com/0zcl/archive/2017/03/22/6580279.html 先看效果图: 登陆admin后的界面: 查看作者: 当然你也可以定制admin ...

  3. IE浏览器从页面向后台Controller传中文值出现乱码问题

    地址前面添加encodeURI() 1. var url = encodeURI('xxxAction.action?para='+中文); $('#cc').combobox({ url : url ...

  4. Server对象,HttpServerUtility类,获取服务器信息

    在Asp.net WebForm中,Server对象是HttpServerUtility类的实例.看下图: 而在Asp.net MVC中,Server对象是HttpServerUtilityBase对 ...

  5. Win10 UEFI +Ghost +intel快速启动 新法完美安装

    http://tieba.baidu.com/p/4767004289?qq-pf-to=pcqq.c2c Win10 如果主板不用Bios 而用UEFI引导启动,速度快,界面好.现在一般都用win1 ...

  6. antd在线换肤定制功能

    最近react项目,用的antd框架,然后看见他的antdPro例子里面有个定制功能很帅,老大说做,那就做吧,鼓捣了一晚终于实现了. 先看预览效果吧 css换肤 入行前端的时候经常看鱼哥(张鑫旭)的博 ...

  7. BASIC-10_蓝桥杯_十进制转十六进制

    示例代码: #include <stdio.h>#define N 16 void dg(int a){ int y = a%N; int next = (a-y)/N; if (next ...

  8. 【Hibernate异常处理-1】java.lang.NoSuchMethodError: javax.persistence.JoinColumn.foreignKey()Ljavax/persistence/ForeignKey;

    原文链接(经验证正确) 说明:其他几个涉及到:NoSuchMethodError: javax.persistence.xxx的处理方法和这相同. JAVAEE6.0中的  javax.persist ...

  9. 【spring框架】spring获取webapplicationcontext,applicationcontext几种方法详解--(转)

    方法一:在初始化时保存ApplicationContext对象代码:ApplicationContext ac = new FileSystemXmlApplicationContext(" ...

  10. 学习笔记之Microsoft Azure

    Microsoft Azure - Wikipedia https://en.wikipedia.org/wiki/Microsoft_Azure Microsoft Azure (formerly  ...