HttpRequestUtil
2018-12-25 本文已影响0人
咖啡机an
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
/**
* Http请求数据
* HttpClient
*/
public class HttpRequestUtil {
private static final Logger LOG = Logger.getLogger(HttpRequestUtil.class);
/**
* 请求数据
*
* @param httpUrl 请求url
* @param params 请求参数可变
* @return
*/
public static String requestData(String httpUrl, String... params) {
BufferedReader in = null;
//http请求地址
StringBuffer http = new StringBuffer();
//http地址主体
http.append(httpUrl).append("?");
int index = 0;
//http地址参数
for (String param : params) {
if (!StringUtils.isEmpty(param)) {
if (index > 0) {
http.append("&").append(param);
} else {
http.append(param);
}
}
index++;
}
//LOG.info("请求地址:"+http.toString());
//请求返回的结果字符串
StringBuilder json = new StringBuilder();
try {
URL data = new URL(http.toString());
URLConnection urlConnection = data.openConnection();
in = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream(), "UTF8"));
String inputLine = null;
while ((inputLine = in.readLine()) != null) {
json.append(inputLine);
}
in.close();
} catch (MalformedURLException e) {
LOG.info("error:" + e);
} catch (IOException e) {
LOG.info("error:" + e);
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return json.toString();
}
public static String postData(String httpUrl, Map<String, String> paramMap) throws Exception {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(httpUrl);
// 打开和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)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
int index = 0;
StringBuffer param = new StringBuffer();
for (Map.Entry entity : paramMap.entrySet()) {
if (index > 0) {
param.append("&");
}
param.append(entity.getKey()).append("=").append(entity.getValue());
index++;
}
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(), "UTF8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
public static String httpUrlConnetionGet(String httpUrl, String... params) {
StringBuffer stringBuffer = null;
try {
//创建URL对象
//http请求地址
StringBuffer http = new StringBuffer();
//http地址主体
http.append(httpUrl).append("?");
int index = 0;
//http地址参数
for (String param : params) {
if (!StringUtils.isEmpty(param)) {
if (index > 0) {
http.append("&").append(param);
} else {
http.append(param);
}
}
index++;
}
URL url = new URL(http.toString().replace(" ", "%20"));
//返回一个URLConnection对象,它表示到URL所引用的远程对象的连接
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//在这里设置一些属性,详细见UrlConnection文档,HttpURLConnection是UrlConnection的子类
//设置连接超时为5秒
httpURLConnection.setConnectTimeout(5000);
//设定请求方式(默认为get)
httpURLConnection.setRequestMethod("GET");
//建立到远程对象的实际连接
httpURLConnection.connect();
//返回打开连接读取的输入流,输入流转化为StringBuffer类型,这一套流程要记住,常用
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF8"));
String line = null;
stringBuffer = new StringBuffer();
while ((line = bufferedReader.readLine()) != null) {
//转化为UTF-8的编码格式
//line = new String(line.getBytes("UTF-8"));
stringBuffer.append(line);
}
bufferedReader.close();
httpURLConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (stringBuffer == null) {
return "";
} else {
return stringBuffer.toString();
}
}
public static String postFile(String actionUrl, Map<String, String> headParams, Map<String, String> params,
Map<String, File> files) throws IOException {
BufferedReader in = null;
DataOutputStream outStream = null;
String result = "";
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--", LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
try {
URL uri = new URL(actionUrl);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setReadTimeout(30 * 1000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
if (headParams != null) {
for (String key : headParams.keySet()) {
conn.setRequestProperty(key, headParams.get(key));
}
}
StringBuilder sb = new StringBuilder();
if (params != null) {
// 首先组拼文本类型的参数
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\""
+ entry.getKey() + "\"" + LINEND);
sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}
}
outStream = new DataOutputStream(conn.getOutputStream());
if (!StringUtils.isEmpty(sb.toString())) {
outStream.write(sb.toString().getBytes());
}
// 发送文件数据
if (files != null) {
for (Map.Entry<String, File> file : files.entrySet()) {
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\""
+ file.getKey() + "\"" + LINEND);
sb1.append("Content-Type: application/octet-stream; charset="
+ CHARSET + LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes());
InputStream is = new FileInputStream(file.getValue());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
is.close();
outStream.write(LINEND.getBytes());
}
}
// 请求结束标志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(), "UTF8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (outStream != null) {
outStream.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
}