http请求相关
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class MyHttpUtils {
private MyHttpUtils() {
throw new IllegalStateException("MyHttpUtils class");
}
public static String encodeURL(String url, String charset) {
try {
url = URLEncoder.encode(url, charset);
} catch (UnsupportedEncodingException ex) {
log.error(ex.getMessage());
}
return url;
}
/**
* 向指定URL发送GET请求(参数都在URL上的).
* URLConnection是所有类的超类,应用程序和URL之间的通信链接.用字节流输出OutputStreamWriter/输入InputStreamReader(当然字符流也可)处理的.
* @param path
* @return
*/
public static String getData(String path) {
if (StringUtils.isNotBlank(path)) {
StringBuilder result = new StringBuilder();
BufferedReader br = null;
try {
URL url = new URL(path);
// URLConnection conn = url.openConnection(); //打开和URL之间的连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET"); // 请求的方式,默认GET
conn.setConnectTimeout(5000); // milliseconds
conn.setReadTimeout(5000); // milliseconds
conn.setDoInput(true); // 是否打开输入流 ,默认true
conn.setDoOutput(true); // 是否打开输出流,默认false
conn.connect(); // 连接
if (conn.getResponseCode() == 200) { // HTTP_OK
// 定义BufferedReader输入流来读取URL的响应
br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
String line;
while ((line = br.readLine()) != null) {
result.append(line.trim()); // result += "\n" +line
}
// 下面是与上面功能另方法读取,推荐上述方法
// InputStream inputStream = conn.getInputStream();
// int size = inputStream.available();
// byte[] bytes = new byte[size];
// inputStream.read(bytes);
// String result = new String(bytes, StandardCharsets.UTF_8);
}
} catch (IOException e) {
log.error(e.getMessage());
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
log.error(ex.getMessage());
}
}
return result.length() > 0 ?result.toString() :"";
}
return "";
}
/**
* 向指定URL发送POST请求(以UrlConnection连接方式).
* URLConnection是所有类的超类,应用程序和URL之间的通信链接.用字节流输出OutputStreamWriter/输入InputStreamReader(当然字符流也可)处理的.
* @param path UNIFIED_ORDER_URL
* @param content
* @param contentType Example "user-agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0)"
* @return
*/
public static String postData(String path, String content, String contentType) {
if (StringUtils.isNotBlank(path) && StringUtils.isNotBlank(content)) {
StringBuilder result = new StringBuilder();
OutputStreamWriter osw = null;
BufferedReader br = null;
try {
URL url = new URL(path);
URLConnection conn = url.openConnection(); // 打开和URL之间的连接
// 发送POST请求必须设置setDoOutput(true)和setDoInput(true)
conn.setDoOutput(true); // post请求,参数要放在http正文内,因此需要设为true, 默认值为false.
// conn.setDoInput(true); //设置是否从UrlConnection读入,默认值为true
conn.setUseCaches(false); // Post请求不能使用缓存,默认值为true
conn.setConnectTimeout(5000); // milliseconds
conn.setReadTimeout(5000); // milliseconds
if (StringUtils.isNotBlank(contentType))
conn.setRequestProperty("content-type", contentType); // 设置内容类型
// 获取URLConnection对象对应的输出流
osw = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8);
osw.write(content);
osw.flush();
// 定义BufferedReader输入流来读取URL的响应
br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
String line;
while ((line = br.readLine()) != null) {
result.append(line.trim()); // result += "\n" +line
}
} catch (IOException e) {
log.error(e.getMessage());
} finally {
try {
if (osw != null)
osw.close();
if (br != null)
br.close();
} catch (IOException ex) {
log.error(ex.getMessage());
}
}
return result.length() > 0 ?result.toString() :"";
}
return "";
}
public static Map<String, String> getParams4Url(String url) {
if (StringUtils.isNotBlank(url)) {
String params = url.substring(url.indexOf("?") + 1, url.length());
String[] arr = params.split("&");
int arrLen = arr.length;
Map<String, String> rtnMap = new HashMap<>(arrLen);
for (int i = 0; i < arrLen; i++) {
String[] kvArr = arr[i].split("=");
rtnMap.put(kvArr[0], (kvArr.length > 1 ?kvArr[1] :""));
}
return rtnMap;
}
return Collections.emptyMap();
}
}