import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.Map.Entry;
@Slf4j
public class HttpHelper {
public String sendPost(String url, String param, Map<String, String> headers) throws Exception{
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(10*1000);
conn.setDoOutput(true); // 发送POST请求必须设置如下两行
conn.setDoInput(true);
conn.setRequestProperty("Charsert", "UTF-8");
if (!MapUtils.isEmpty(headers)) {
for (Entry<String, String> entry : headers.entrySet()) {
conn.addRequestProperty(entry.getKey(), entry.getValue());
}
}
out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
log.error("HTTP请求路径时错误:" + url, e.getMessage());
throw e; // 异常外抛
} finally{
try{
if(out!=null)out.close();
if(in!=null) in.close();
}
catch(Exception ex){
}
}
return result;
}
public static String sendPostToFrom(String url, String param, Map<String, String> headers) {
return sendConnection(url,param,headers,"POST","application/x-www-form-urlencoded");
}
public static String sendPostToJson(String url, String param, Map<String, String> headers) {
return sendConnection(url,param,headers,"POST","application/json; charset=UTF-8");
}
public static String sendPost1(String url, String param, Map<String, String> headers) {
return sendConnection(url,param,headers,"POST","");
}
public static String sendGetToFrom(String url, String param, Map<String, String> headers) {
return sendConnection(url,param,headers,"GET","application/x-www-form-urlencoded");
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数
* @return 所代表远程资源的响应结果
*/
public static String sendConnection(String url, String param,Map<String, String> headers,String method,String contentType) {
String result = "";
PrintWriter out = null;
HttpURLConnection connection = null;
try {
URL postUrl = new URL(url);
// 打开和URL之间的连接
connection = (HttpURLConnection) postUrl.openConnection();
connection = setConnection(connection, method, contentType);
connection = fillHeaders(connection,headers);
//1.获取URLConnection对象对应的输出流
out = new PrintWriter(connection.getOutputStream());
out.print(param);
out.flush();
// 定义BufferedReader输入流来读取URL的响应
result = getResult(connection);
} catch (Exception e) {
log.error("发送 POST 请求出现异常!"+e );
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (connection != null) {
//关闭连接
connection.disconnect();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
return result;
}
/**
* 定义BufferedReader输入流来读取URL的响应
* @param connection
* @return
*/
private static String getResult(HttpURLConnection connection) {
BufferedReader in = null;
String result = "";
try {
if (connection.getResponseCode() == 200) {
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
/**
* @param connection
* @param headers
* @return
*/
private static HttpURLConnection fillHeaders(HttpURLConnection connection, Map<String, String> headers) {
if (!MapUtils.isEmpty(headers)) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
connection.addRequestProperty(entry.getKey(), entry.getValue());
}
}
return connection;
}
/**
*
* @param connection
* @param method 请求方式:POST、GET
* @param contentType 请求格式
* form表单是:application/x-www-form-urlencoded
* json是:application/json; charset=UTF-8
* @return
* @throws IOException
*/
private static HttpURLConnection setConnection(HttpURLConnection connection, String method, String contentType) throws IOException {
// 在connect之前,设置通用的请求属性
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.setRequestProperty("Charsert", "UTF-8");
connection.setConnectTimeout(10000);
connection.setReadTimeout(60000);
if("POST".equals(method)){
// 发送POST请求必须设置如下两行,参数要放在http正文内
connection.setDoOutput(true);
connection.setDoInput(true);
// Post 请求不使用缓存
connection.setUseCaches(false);
}
// 默认是 GET方式
connection.setRequestMethod(StringUtil.isNullOrEmpty(method)?"GET":method);
// 配置本次连接的Content-type,form表单是"application/x-www-form-urlencoded",json是"application/json"等
if (!StringUtil.isNullOrEmpty(contentType)){
connection.setRequestProperty("Content-Type", contentType);
}
connection.connect();
return connection;
}
}