基于HttpClient的HttpUtils(后台访问URL)
最近做在线支付时遇到需要以后台方式访问URL并获取其返回的数据的问题,在网络上g了一把,发现在常用的还是Apache的HttpClient。因为以经常要用到的原故,因此我对其进行了一些简单的封装,在此将代码贴一来,希望对有需要的朋友有所帮助,呵呵...
HttpUtils.java中有两个公共的静态方法,一个是URLPost,另一个是URLGet,一目了然,前者是提供POST方式提交数据的,后者是提供GET方式提交数据的。其中所需要传送的数据以Map的方式传入,剩下的工作就交给我这个HttpUtils吧!当然如果Http服务器端对所提交的数据的编码有要求的话,也没问题,你可以传入UTF-8或者GBK,当然大家还可自行增加。
下面是源代码,如果使用中有什么问题,欢迎大家提出。
- import java.io.IOException;
- import java.io.UnsupportedEncodingException;
- import java.net.URLEncoder;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Set;
- import org.apache.commons.httpclient.HttpClient;
- import org.apache.commons.httpclient.HttpException;
- import org.apache.commons.httpclient.HttpStatus;
- import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
- import org.apache.commons.httpclient.methods.GetMethod;
- import org.apache.commons.httpclient.methods.PostMethod;
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- /**
- * HTTP工具类
- *
- * @author lixiangyang
- *
- */
- public class HttpUtils {
- private static Log log = LogFactory.getLog(HttpUtils.class);
- /**
- * 定义编码格式 UTF-8
- */
- public static final String URL_PARAM_DECODECHARSET_UTF8 = "UTF-8";
- /**
- * 定义编码格式 GBK
- */
- public static final String URL_PARAM_DECODECHARSET_GBK = "GBK";
- private static final String URL_PARAM_CONNECT_FLAG = "&";
- private static final String EMPTY = "";
- private static MultiThreadedHttpConnectionManager connectionManager = null;
- private static int connectionTimeOut = 25000;
- private static int socketTimeOut = 25000;
- private static int maxConnectionPerHost = 20;
- private static int maxTotalConnections = 20;
- private static HttpClient client;
- static{
- connectionManager = new MultiThreadedHttpConnectionManager();
- connectionManager.getParams().setConnectionTimeout(connectionTimeOut);
- connectionManager.getParams().setSoTimeout(socketTimeOut);
- connectionManager.getParams().setDefaultMaxConnectionsPerHost(maxConnectionPerHost);
- connectionManager.getParams().setMaxTotalConnections(maxTotalConnections);
- client = new HttpClient(connectionManager);
- }
- /**
- * POST方式提交数据
- * @param url
- * 待请求的URL
- * @param params
- * 要提交的数据
- * @param enc
- * 编码
- * @return
- * 响应结果
- * @throws IOException
- * IO异常
- */
- public static String URLPost(String url, Map<String, String> params, String enc){
- String response = EMPTY;
- PostMethod postMethod = null;
- try {
- postMethod = new PostMethod(url);
- postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + enc);
- //将表单的值放入postMethod中
- Set<String> keySet = params.keySet();
- for(String key : keySet){
- String value = params.get(key);
- postMethod.addParameter(key, value);
- }
- //执行postMethod
- int statusCode = client.executeMethod(postMethod);
- if(statusCode == HttpStatus.SC_OK) {
- response = postMethod.getResponseBodyAsString();
- }else{
- log.error("响应状态码 = " + postMethod.getStatusCode());
- }
- }catch(HttpException e){
- log.error("发生致命的异常,可能是协议不对或者返回的内容有问题", e);
- e.printStackTrace();
- }catch(IOException e){
- log.error("发生网络异常", e);
- e.printStackTrace();
- }finally{
- if(postMethod != null){
- postMethod.releaseConnection();
- postMethod = null;
- }
- }
- return response;
- }
- /**
- * GET方式提交数据
- * @param url
- * 待请求的URL
- * @param params
- * 要提交的数据
- * @param enc
- * 编码
- * @return
- * 响应结果
- * @throws IOException
- * IO异常
- */
- public static String URLGet(String url, Map<String, String> params, String enc){
- String response = EMPTY;
- GetMethod getMethod = null;
- StringBuffer strtTotalURL = new StringBuffer(EMPTY);
- if(strtTotalURL.indexOf("?") == -1) {
- strtTotalURL.append(url).append("?").append(getUrl(params, enc));
- } else {
- strtTotalURL.append(url).append("&").append(getUrl(params, enc));
- }
- log.debug("GET请求URL = \n" + strtTotalURL.toString());
- try {
- getMethod = new GetMethod(strtTotalURL.toString());
- getMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + enc);
- //执行getMethod
- int statusCode = client.executeMethod(getMethod);
- if(statusCode == HttpStatus.SC_OK) {
- response = getMethod.getResponseBodyAsString();
- }else{
- log.debug("响应状态码 = " + getMethod.getStatusCode());
- }
- }catch(HttpException e){
- log.error("发生致命的异常,可能是协议不对或者返回的内容有问题", e);
- e.printStackTrace();
- }catch(IOException e){
- log.error("发生网络异常", e);
- e.printStackTrace();
- }finally{
- if(getMethod != null){
- getMethod.releaseConnection();
- getMethod = null;
- }
- }
- return response;
- }
- /**
- * 据Map生成URL字符串
- * @param map
- * Map
- * @param valueEnc
- * URL编码
- * @return
- * URL
- */
- private static String getUrl(Map<String, String> map, String valueEnc) {
- if (null == map || map.keySet().size() == 0) {
- return (EMPTY);
- }
- StringBuffer url = new StringBuffer();
- Set<String> keys = map.keySet();
- for (Iterator<String> it = keys.iterator(); it.hasNext();) {
- String key = it.next();
- if (map.containsKey(key)) {
- String val = map.get(key);
- String str = val != null ? val : EMPTY;
- try {
- str = URLEncoder.encode(str, valueEnc);
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- url.append(key).append("=").append(str).append(URL_PARAM_CONNECT_FLAG);
- }
- }
- String strURL = EMPTY;
- strURL = url.toString();
- if (URL_PARAM_CONNECT_FLAG.equals(EMPTY + strURL.charAt(strURL.length() - 1))) {
- strURL = strURL.substring(0, strURL.length() - 1);
- }
- return (strURL);
- }
- }
基于HttpClient的HttpUtils(后台访问URL)的更多相关文章
- nginx针对某个url限制ip访问,常用于后台访问限制【转】
假如我的站点后台地址为: http://www.abc.net/admin.php 那么我想限制只有个别ip可以访问后台,那么需要在配置文件中增加: location ~ .*admin.* { al ...
- Spring RestTemplate: 比httpClient更优雅的Restful URL访问, java HttpPost with header
{ "Author": "tomcat and jerry", "url":"http://www.cnblogs.com/tom ...
- 基于shiro+jwt的真正rest url权限管理,前后端分离
代码地址如下:http://www.demodashi.com/demo/13277.html bootshiro & usthe bootshiro是基于springboot+shiro+j ...
- 利用javascript Location访问Url,重定向,刷新页面
网上转来了, 方便以后查询参考 本文介绍怎么使用javascript Location对象读和修改Url.怎么重载或刷新页面.javascript提供了许多方法访问,修改当前用户在浏览器中访问的url ...
- 基于SpringBoot的项目管理后台
代码地址如下:http://www.demodashi.com/demo/13943.html 一.项目简介 在使用本项目之前,需要对SpringBoot,freemaker,layui,flyway ...
- 基于WCF 的远程数据库服务访问技术
原文出处:http://www.lw80.cn/shuji/jsjlw/13588Htm.Htm摘要:本文介绍了使用WCF 建立和运行面向服务(SOA)的数据库服务的系统结构和技术要素,分析了WCF ...
- SpringCloud-Config通过Java访问URL对敏感词加密解密
特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过.如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/ ...
- 基于vue模块化开发后台系统——准备工作
文章目录如下:项目效果预览地址项目开源代码基于vue模块化开发后台系统--准备工作基于vue模块化开发后台系统--构建项目基于vue模块化开发后台系统--权限控制 前言 本文章是以学习为主,练习一下v ...
- Django项目:CRM(客户关系管理系统)--84--74PerfectCRM实现CRM权限和权限组限制访问URL
#models.py # ————————01PerfectCRM基本配置ADMIN———————— from django.db import models # Create your models ...
随机推荐
- 【转】RS232、RS485、TTL电平、CMOS电平
原文网址:http://blog.sina.com.cn/s/blog_63a0638101018grc.html RS232.RS485.TTL电平.CMOS电平 什么是TTL电平.CMOS电平.R ...
- OAuth 2.0:Bearer Token、MAC Token区别
Access Token 类型介绍 介绍两种类型的Access Token:Bearer类型和MAC类型 区别项 Bearer Token MAC Token 1 (优点) 调用简单,不需要对请求进行 ...
- mysql 聚簇索引、非聚簇索引的区别
索引分为聚簇索引和非聚簇索引. 以一本英文课本为例,要找第8课,直接翻书,若先翻到第5课,则往后翻,再翻到第10课,则又往前翻.这本书本身就是一个索引,即"聚簇索引". 如果要找& ...
- PHP中header的用法总结
来源 :http://blog.sina.com.cn/s/blog_7298f36f01011dxv.html header的用法 header()函数的作用是:发送一个原始 HTTP 标头[Htt ...
- 【textarea】在JSP上添加textarea-文本域 调试使用
<body> <form name="dataEventDisplay"> <table border="2" bordercol ...
- bzoj1050 旅行
Description 给你一个无向图,N(N<=500)个顶点, M(M<=5000)条边,每条边有一个权值Vi(Vi<30000).给你两个顶点S和T,求一条路径,使得路径上最大 ...
- windows任务计划程序 坑
- java web程序 jdbc连接数据库错误排查方法
学习jsp.我遇到了麻烦,我总是看不懂500错误,因为每次都显示整个页面的错误,都是英文 我看不懂,后来,把他弄烦了,我也烦了,比起学习java.那个异常可以很简单的就知道.现在解决 了第一个问题,5 ...
- ActiveMQ 高可用集群安装、配置(ZooKeeper + LevelDB)
ActiveMQ 高可用集群安装.配置(ZooKeeper + LevelDB) 1.ActiveMQ 集群部署规划: 环境: JDK7 版本:ActiveMQ 5.11.1 ZooKeeper 集群 ...
- php for 循环使用实例介绍
for 循环用于您预先知道脚本需要运行的次数的情况. 语法 for (初始值; 条件; 增量) { 要执行的代码; } 参数: 初始值:主要是初始化一个变量值,用于设置一个计数器(但可以是任何在循环的 ...