Java常用的HTTP请求方式
第一种:jdk中自带的URLConnection
示例代码如下:
// An highlighted block
public synchronized static String URLConnectionPost(String url, Map<String, String> header,
Map<String, String> params, String body) throws ConnectException {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
if (header != null && !header.isEmpty()) {
Set<String> headers = header.keySet();
for (String key : headers) {
conn.setRequestProperty(key, header.get(key));
}
}
if ((params != null && !params.isEmpty()) && (StringUtils.isNotEmpty(body))) {
System.out.println("传入参数异常,data 和 body 不能同时传入");
throw new java.net.ConnectException("传入参数异常,data 和 body 不能同时传入");
}
/**
* 参数
*/
StringBuffer p = new StringBuffer();
if (params != null && !params.isEmpty()) {
Set<String> param = params.keySet();
for (String k : param) {
p.append(k + "=" + params.get(k) + "&");
}
}
if (StringUtils.isNotEmpty(body)) {
p.append(body);
}
if (p.length() > 0) {
p = p.deleteCharAt(p.length() - 1);
}
// 发送POST请求必须设置如下两行
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(p.toString());
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
throw new java.net.ConnectException("请求错误,status code is[" + result + "]");
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
第二种:apache的httpclient
示例代码如下:
// An highlighted block
public synchronized static byte[] CustomPostMethodPost(String url, String charset, Map<String, String> header,
Map<String, String> data, String body) throws Exception {
byte[] result = null;
CustomPostMethod postMethod = new CustomPostMethod(url);
try {
HttpClient client = getClient(charset);
if (header != null && !header.isEmpty()) {
Set<String> headers = header.keySet();
for (String key : headers) {
postMethod.setRequestHeader(key, header.get(key));
}
}
if (data != null && !data.isEmpty()) {
Set<String> keys = data.keySet();
NameValuePair[] ps = new NameValuePair[keys.size()];
int index = 0;
for (String k : keys) {
ps[index++] = new NameValuePair(k, data.get(k));
}
postMethod.setRequestBody(ps);
}
postMethod.setQueryString(body);
int statusCode = client.executeMethod(postMethod);
Header[] _map = postMethod.getResponseHeaders();
Map<String, String> map = new HashMap<String, String>();
for (Header h : _map) {
map.put(h.getName(), h.getValue());
}
if (statusCode == 200) {
result = postMethod.getResponseBody();
return result;
} else if (statusCode == 302) {
result = postMethod.getResponseBody();
return result;
}
postMethod.abort();
throw new java.net.ConnectException("请求错误,status code is[" + statusCode + "]");
} catch (Exception e) {
postMethod.abort();
throw e;
} finally {
postMethod.releaseConnection();
}
}
private static HttpClient getClient(String charset) {
HttpClient client = new HttpClient(connectionManager);
HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams();
params.setConnectionTimeout(30000);
params.setSoTimeout(30000);
params.setDefaultMaxConnectionsPerHost(500);
params.setMaxTotalConnections(1500);
params.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
HttpClientParams hcp = client.getParams();
hcp.setParameter("http.connection.timeout", 20 * 1000L);
hcp.setParameter("http.connection-manager.timeout", 20 * 1000L);
hcp.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, charset);
hcp.setAuthenticationPreemptive(true);
return client;
}
public class CustomPostMethod extends
org.apache.commons.httpclient.methods.PostMethod{
public CustomPostMethod(String url){
super(url);
}
public String getResponseBodyAsString() throws IOException {
GZIPInputStream gzin;
if (getResponseBody() != null || getResponseStream() != null) {
if (getResponseHeader("Content-Encoding") != null
&& getResponseHeader("Content-Encoding").getValue()
.toLowerCase().indexOf("gzip") > -1) {
// For GZip response
InputStream is = getResponseBodyAsStream();
gzin = new GZIPInputStream(is);
InputStreamReader isr = new InputStreamReader(gzin,
getResponseCharSet());
java.io.BufferedReader br = new java.io.BufferedReader(isr);
StringBuffer sb = new StringBuffer();
String tempbf;
while ((tempbf = br.readLine()) != null) {
sb.append(tempbf);
sb.append("\r\n");
}
isr.close();
gzin.close();
return sb.toString();
} else {
// For deflate response
return super.getResponseBodyAsString();
}
} else {
return null;
}
}
}