HTTP请求工具类:
package util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
public class HttpUtil {
final static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
/**
* Post 请求超时时间和读取数据的超时时间均为2000ms。
*
* @param urlPath
* post请求地址
* @param parameterData
* post请求参数
* @return String json字符串,成功:code=1001,否者为其他值
* @throws Exception
* 链接超时异常、参数url错误格式异常
*/
public static String doPost(String urlPath, String parameterData,
String who, String ip) throws Exception {
if (null == urlPath || null == parameterData) { // 避免null引起的空指针异常
return "";
}
URL localURL = new URL(urlPath);
URLConnection connection = localURL.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
httpURLConnection.setDoOutput(true);
if (!StringUtils.isEmpty(who)) {
httpURLConnection.setRequestProperty("who", who);
}
if (!StringUtils.isEmpty(ip)) {
httpURLConnection.setRequestProperty("clientIP", ip);
}
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
httpURLConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
httpURLConnection.setRequestProperty("Content-Length",
String.valueOf(parameterData.length()));
httpURLConnection.setConnectTimeout(18000);
httpURLConnection.setReadTimeout(18000);
OutputStream outputStream = null;
OutputStreamWriter outputStreamWriter = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
StringBuilder resultBuffer = new StringBuilder();
String tempLine = null;
try {
outputStream = httpURLConnection.getOutputStream();
outputStreamWriter = new OutputStreamWriter(outputStream);
outputStreamWriter.write(parameterData.toString());
outputStreamWriter.flush();
if (httpURLConnection.getResponseCode() >= 300) {
throw new Exception(
"HTTP Request is not success, Response code is "
+ httpURLConnection.getResponseCode());
}
inputStream = httpURLConnection.getInputStream(); // 真正的发送请求到服务端
inputStreamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStreamReader);
while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
}
} finally {
if (outputStreamWriter != null) {
outputStreamWriter.close();
}
if (outputStream != null) {
outputStream.close();
}
if (reader != null) {
reader.close();
}
if (inputStreamReader != null) {
inputStreamReader.close();
}
if (inputStream != null) {
inputStream.close();
}
}
return resultBuffer.toString();
}
/**
* Post 请求超时时间和读取数据的超时时间均为2000ms。
*
* @param urlPath
* post请求地址
* @param parameterData
* post请求参数
* @return String json字符串,成功:code=1001,否者为其他值
* @throws Exception
* 链接超市异常、参数url错误格式异常
*/
public static String doPostByJSON(String urlPath, JSONObject parameterData) throws Exception {
if (null == urlPath || null == parameterData) { // 避免null引起的空指针异常
return "";
}
URL localURL = new URL(urlPath);
URLConnection connection = localURL.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
httpURLConnection.setDoOutput(true);
Set<String> keySet = parameterData.keySet();
Iterator it = keySet.iterator();
while(it.hasNext()){
String key = it.next().toString();
if("url".equals(key)){
continue;
}
String value = parameterData.get(key).toString();
connection.setRequestProperty(key, value);
}
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
httpURLConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
httpURLConnection.setRequestProperty("Content-Length",String.valueOf(parameterData.toJSONString().length()));
httpURLConnection.setConnectTimeout(18000);
httpURLConnection.setReadTimeout(18000);
OutputStream outputStream = null;
OutputStreamWriter outputStreamWriter = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
StringBuilder resultBuffer = new StringBuilder();
String tempLine = null;
try {
outputStream = httpURLConnection.getOutputStream();
outputStreamWriter = new OutputStreamWriter(outputStream);
outputStreamWriter.write(parameterData.toString());
outputStreamWriter.flush();
if (httpURLConnection.getResponseCode() >= 300) {
throw new Exception(
"HTTP Request is not success, Response code is "
+ httpURLConnection.getResponseCode());
}
inputStream = httpURLConnection.getInputStream(); // 真正的发送请求到服务端
inputStreamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStreamReader);
while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
}
} finally {
if (outputStreamWriter != null) {
outputStreamWriter.close();
}
if (outputStream != null) {
outputStream.close();
}
if (reader != null) {
reader.close();
}
if (inputStreamReader != null) {
inputStreamReader.close();
}
if (inputStream != null) {
inputStream.close();
}
}
return resultBuffer.toString();
}
public static String doPost(String url, Map<String, Object> params)
throws Exception {
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, Object> entry : params.entrySet()) {
sb.append(entry.getKey()).append("=").append(entry.getValue())
.append("&");
}
// no matter for the last '&' character
return doPost(url, sb.toString(), "", "");
}
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param, String who, String ip) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url;
if (!"".equals(param)) {
urlNameString = urlNameString + "?" + param;
}
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
if (!StringUtils.isEmpty(who)) {
connection.setRequestProperty("who", who);
}
if (!StringUtils.isEmpty(ip)) {
connection.setRequestProperty("clientIP", ip);
}
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
//bufReader = new BufferedReader(new InputStreamReader(in, "utf-8"));
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
logger.warn("发送GET请求出现异常!", e);
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
logger.warn("fail to close inputStream.", e2);
}
}
return result;
}
public static String sendGet(String url, Map<String, Object> params)
throws Exception {
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, Object> entry : params.entrySet()) {
sb.append(entry.getKey()).append("=").append(entry.getValue())
.append("&");
}
// no matter for the last '&' character
return sendGet(url, sb.toString(), "", "");
}
public static String sendGet(String url, JSONObject parameterData) throws Exception {
StringBuffer sb = new StringBuffer();
Set<String> keySet = parameterData.keySet();
Iterator it = keySet.iterator();
while(it.hasNext()){
String key = it.next().toString();
if("param".equals(key)){
String value = parameterData.get(key).toString();
sb.append(key).append("=").append(URLEncoder.encode(value, "UTF-8")).append("&");
}else{
String value = parameterData.get(key).toString();
sb.append(key).append("=").append(value).append("&");
}
}
// no matter for the last '&' character
System.out.println(sb.toString());
return sendGet(url, sb.toString(), "", "");
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, Map<String,Object> param) throws Exception {
// PrintWriter out = null;
OutputStreamWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.setRequestProperty("X-HW-ID", "videoAnalysisAPI");
conn.setRequestProperty("X-HW-APPKEY", "J5ejD2Hh9in+ex7oMS+f0Q==");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// out = new PrintWriter(conn.getOutputStream());
// out = new OutputStreamWriter(conn.getOutputStream(), "ISO-8859-1"); // 8859_1
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); // 8859_1
out.write(JSONObject.toJSONString(param));
// out.write("{\"a\":\"b\"}");
out.flush();
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(),"utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
throw e;
}
finally{
try{
if(out!=null) out.close();
if(in!=null)in.close();
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
public static String sendPost(String url, String param) throws Exception {
// PrintWriter out = null;
System.out.println(1111111111);
OutputStreamWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
// 发送POST请求必须设置如下两行
// 发送POST请求必须设置如下两行
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
// out = new PrintWriter(conn.getOutputStream());
out = new OutputStreamWriter(conn.getOutputStream(), "utf-8"); // 8859_1
out.write(param); // post的关键所在
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(),"utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
throw e;
}
finally{
try{
if(out!=null) out.close();
if(in!=null)in.close();
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
}