import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* @author ParanoidCAT
* @since JDK 1.8
*/
public class HttpUtils {
private static final String POST = "POST";
private HttpUtils() throws Exception {
throw new Exception("no HttpUtils instance should be created");
}
/**
* 发送GET请求
*
* @param urlAddress 请求地址
* @param requestProperties 请求属性
* @param parameterMap 参数
* @return 响应字符串
*/
public static String get(String urlAddress, Map<String, String> requestProperties, Map<String, String> parameterMap) {
try {
String requestParameters = Optional
.ofNullable(parameterMap)
.orElseGet(Collections::emptyMap)
.entrySet()
.stream()
.map(entry -> entry.getKey() + "=" + entry.getValue())
.collect(Collectors.joining("&"));
HttpURLConnection httpUrlConnection = (HttpURLConnection) generateUrlConnection(isNotEmpty(requestParameters) ? urlAddress + "?" + requestParameters : urlAddress);
Optional
.ofNullable(requestProperties)
.orElseGet(Collections::emptyMap)
.forEach(httpUrlConnection::addRequestProperty);
httpUrlConnection.connect();
return getResponseBody(httpUrlConnection);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* 发送POST请求
*
* @param urlAddress 请求地址
* @param requestProperties 请求属性
* @param output 参数
* @return 响应字符串
*/
public static String post(String urlAddress, Map<String, String> requestProperties, String output) {
try {
HttpURLConnection httpUrlConnection = (HttpURLConnection) generateUrlConnection(urlAddress);
Optional.ofNullable(requestProperties).orElseGet(Collections::emptyMap).forEach(httpUrlConnection::addRequestProperty);
httpUrlConnection.setRequestMethod(POST);
if (isNotEmpty(output)) {
httpUrlConnection.setDoOutput(Boolean.TRUE);
try (PrintWriter printWriter = new PrintWriter(httpUrlConnection.getOutputStream())) {
printWriter.print(output);
}
}
httpUrlConnection.connect();
return getResponseBody(httpUrlConnection);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* 获取Url链接
*
* @param urlAddress 请求地址
* @return Url链接
* @throws IOException IO异常
*/
private static URLConnection generateUrlConnection(String urlAddress) throws IOException {
URLConnection urlConnection = new URL(urlAddress).openConnection();
urlConnection.setDoInput(Boolean.TRUE);
urlConnection.setUseCaches(Boolean.FALSE);
urlConnection.setConnectTimeout(60 * 1000);
urlConnection.setReadTimeout(60 * 1000);
return urlConnection;
}
/**
* 获取响应报文
*
* @param httpUrlConnection Url链接
* @return 响应报文
* @throws IOException IO异常
*/
private static String getResponseBody(HttpURLConnection httpUrlConnection) throws IOException {
int responseCode = httpUrlConnection.getResponseCode();
String responseBody;
if (HttpURLConnection.HTTP_OK == responseCode) {
try (InputStream inputStream = httpUrlConnection.getInputStream()) {
return getTextFromStream(inputStream);
}
} else {
try (InputStream inputStream = httpUrlConnection.getErrorStream()) {
responseBody = getTextFromStream(inputStream);
} catch (IOException e) {
responseBody = null;
}
throw new IOException("Http请求失败-responseCode:" + responseCode + ",responseMessage:" + httpUrlConnection.getResponseMessage() + ",responseBody:" + responseBody);
}
}
/**
* 从输入流中获取文本
*
* @param inputStream 输入流
* @return 文本
* @throws IOException IO异常
*/
private static String getTextFromStream(InputStream inputStream) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
if (inputStream != null) {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
stringBuilder.append(new String(buffer, 0, length, StandardCharsets.UTF_8));
}
}
return stringBuilder.toString();
}
/**
* 判断对象字符串不是空字符串
*
* @param string 对象字符串
* @return true/false
*/
private static boolean isNotEmpty(String string) {
return string != null && !"".equals(string);
}
}