Java-基于HttpClient的java后台访问URL

写支付相关东西遇到需要在后台访问url,搜了搜找到一篇不错的代码,收藏下来以留后用。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
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);
}
}
打赏
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  • © 2017-2023 王丹鹏
  • Powered by Hexo Theme Ayer
  • 冀ICP备15029707号

请我喝杯咖啡吧~

支付宝
微信