import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.Logger;
/**
* @Author: 冯崇
* @Version:V1.0
*/
public class HttpRequestUtil {
protected static final Logger log = Logger.getLogger(HttpRequestUtil.class);
/**
* HttpClient 模拟POST请求 方法说明
*
* @Discription:扩展说明
* @param url
* @param params
* @return String
*/
public static String postRequest(String url, Map<String, String> params) {
//构造HttpClient的实例
HttpClient httpClient = new HttpClient();
//创建POST方法的实例
PostMethod postMethod = new PostMethod(url);
//设置请求头信息
postMethod.setRequestHeader("Connection", "close");
//添加参数
for (Map.Entry<String, String> entry : params.entrySet()) {
postMethod.addParameter(entry.getKey(), entry.getValue());
}
//使用系统提供的默认的恢复策略,设置请求重试处理,用的是默认的重试处理:请求三次
httpClient.getParams().setBooleanParameter("http.protocol.expect-continue", false);
//接收处理结果
String result = null;
try {
//执行Http Post请求
httpClient.executeMethod(postMethod);
//返回处理结果
result = postMethod.getResponseBodyAsString();
} catch (HttpException e) {
// 发生致命的异常,可能是协议不对或者返回的内容有问题
log.error("请检查输入的URL: {}", e);
e.printStackTrace();
} catch (IOException e) {
// 发生网络异常
log.error("发生网络异常: {}", e);
e.printStackTrace();
} finally {
//释放链接
postMethod.releaseConnection();
//关闭HttpClient实例
if (httpClient != null) {
((SimpleHttpConnectionManager) httpClient.getHttpConnectionManager()).shutdown();
httpClient = null;
}
}
return result;
}
/**
* HttpClient 模拟GET请求 方法说明
*
* @Discription:扩展说明
* @param url
* @param params
* @return String
*/
public static String getRequest(String url, Map<String, String> params) {
//构造HttpClient实例
HttpClient client = new HttpClient();
//拼接参数
String paramStr = "";
for (String key : params.keySet()) {
paramStr = paramStr + "&" + key + "=" + params.get(key);
}
paramStr = paramStr.substring(1);
try {
paramStr = URLEncoder.encode(paramStr, "utf-8");
} catch (UnsupportedEncodingException e1) {
log.error("请检查输入的URL: {}", e1);
}
//创建GET方法的实例
GetMethod method = new GetMethod(url + "?" + paramStr);
//接收返回结果
String result = null;
try {
//执行HTTP GET方法请求
client.executeMethod(method);
//返回处理结果
result = method.getResponseBodyAsString();
} catch (HttpException e) {
// 发生致命的异常,可能是协议不对或者返回的内容有问题
log.error("请检查输入的URL: {}", e);
e.printStackTrace();
} catch (IOException e) {
// 发生网络异常
log.error("https请求异常: {}", e);
e.printStackTrace();
} finally {
//释放链接
method.releaseConnection();
//关闭HttpClient实例
if (client != null) {
((SimpleHttpConnectionManager) client.getHttpConnectionManager()).shutdown();
client = null;
}
}
return result;
}
/**
* PSOT方式发送HTTP请求
*
* @param url 请求地址
* @param data 请求参数
*/
public static String post(String url, String data) {
HttpURLConnection http = null;
PrintWriter out = null;
BufferedReader reader = null;
try {
//创建连接
URL urlPost = new URL(url);
http = (HttpURLConnection) urlPost.openConnection();
http.setDoOutput(true);
http.setDoInput(true);
http.setRequestMethod("POST");
http.setUseCaches(false);
http.setInstanceFollowRedirects(true);
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.connect();
//POST请求
OutputStreamWriter outWriter = new OutputStreamWriter(http.getOutputStream(), "utf-8");
out = new PrintWriter(outWriter);
out.print(data);
out.flush();
out.close();
out = null;
//读取响应
reader = new BufferedReader(new InputStreamReader(http.getInputStream()));
String lines;
StringBuffer sb = new StringBuffer("");
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
sb.append(lines);
}
reader.close();
reader = null;
// System.out.println(sb.toString());
return sb.toString();
} catch (Exception e) {
// TODO Auto-generated catch block
// e.printStackTrace();
return null;
} finally {
if (null != http) http.disconnect();
if (null != out) out.close();
try {
if (null != reader) reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* PSOT方式发送HTTP请求
*
* @param requestUrl 请求地址
* @param outputStr 请求参数
*/
public static JSONObject httpPostRequest(String requestUrl, String outputStr) {
PostMethod post = new PostMethod(requestUrl);
post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
post.addParameter("para", outputStr);
String info = null;
HttpClient httpclient = new HttpClient();
try {
httpclient.executeMethod(post);
info = new String(post.getResponseBody(), "UTF-8");
} catch (Exception e) {
log.error("https请求异常: {}", e);
}
// System.out.println(info);
return JSONObject.fromObject(info);
}
}