通过java.net.HttpURLConnection类实现http post发送Content-Type为multipart/form-data的请求。
json处理使用com.fasterxml.jackson
图片压缩使用net.coobird.thumbnailator
log使用org.slf4j
private static final Charset charset = StandardCharsets.UTF_8;
public enum Method {
POST, GET
}
private static final Logger logger = LoggerFactory.getLogger(HttpHandler.class);
public static JsonNode getResponseWithHeaders(String urlString, Map headerMap) throws HttpAccessException {
try {
// logger.debug("Requesting: {}", urlString);
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
// connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON);
connection.setRequestProperty("Accept", MediaType.APPLICATION_JSON);
connection.setRequestMethod("GET");
if (headerMap != null) {
headerMap.entrySet().forEach((header) -> {
connection.setRequestProperty(header.getKey(), header.getValue());
});
}
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
return JsonUtil.getObjectMapper().readTree(new InputStreamReader(connection.getInputStream(), charset));
} else {
logger.error("Bad response code: {}", responseCode);
throw new HttpAccessException("Bad response code: " + responseCode);
}
} catch (MalformedURLException e) {
throw new HttpAccessException("Malformed url", e);
} catch (JsonProcessingException parseException) {
throw new HttpAccessException("Failed to parse response as JSON", parseException);
} catch (IOException e) {
throw new HttpAccessException("IOException", e);
}
}
public static JsonNode requestJsonResponse(String urlString, Method method, String body) throws HttpAccessException {
try {
// logger.debug("Requesting: {}", urlString);
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON);
connection.setRequestProperty("Accept", MediaType.APPLICATION_JSON);
connection.setRequestMethod(method == Method.POST ? "POST" : "GET");
if (body != null) {
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), charset);
logger.debug("Sending payload: {}", body);
writer.write(body);
writer.close();
}
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
return JsonUtil.getObjectMapper().readTree(new InputStreamReader(connection.getInputStream(), charset));
} else {
logger.error("Bad response code: {}", responseCode);
throw new HttpAccessException("Bad response code: " + responseCode);
}
} catch (MalformedURLException e) {
throw new HttpAccessException("Malformed url", e);
} catch (JsonProcessingException parseException) {
throw new HttpAccessException("Failed to parse response as JSON", parseException);
} catch (IOException e) {
throw new HttpAccessException("IOException", e);
}
}
public T postReadClassResponse(String urlString, Object body, Class responseClass) throws HttpAccessException {
try {
// logger.debug("Requesting: {}", urlString);
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON_VALUE);
connection.setRequestProperty("Accept", MediaType.APPLICATION_JSON_VALUE);
connection.setRequestMethod("POST");
objectMapper.writeValue(connection.getOutputStream(), body);
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
return objectMapper.readValue(connection.getInputStream(), responseClass);
// return objectMapper.readTree(new InputStreamReader(connection.getInputStream(), charset));
} else {
// log.error("Bad response code: {}", responseCode);
throw new HttpAccessException("Bad response code: " + responseCode);
}
} catch (MalformedURLException e) {
throw new HttpAccessException("Malformed url", e);
} catch (JsonProcessingException parseException) {
throw new HttpAccessException("Failed to parse response as JSON", parseException);
} catch (IOException e) {
throw new HttpAccessException("IOException", e);
}
}
public static String postApplicationFormUrlencoded(String urlString, Map body) throws HttpAccessException {
StringBuilder sb = new StringBuilder();
if (body != null && !body.isEmpty()) {
body.entrySet().forEach(e -> {
sb.append(e.getKey()).append('=');
sb.append(e.getValue()).append('&');
});
sb.deleteCharAt(sb.length() - 1);
}
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
connection.setRequestProperty("Accept", MediaType.WILDCARD);
connection.setRequestMethod("POST");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), charset);
writer.write(sb.toString());
writer.close();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), charset));
StringBuilder buffer = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} else {
int code = connection.getResponseCode();
logger.error("Bad response code: {}", code);
throw new HttpAccessException("Bad response code: " + code);
}
} catch (MalformedURLException e) {
throw new HttpAccessException("Malformed url", e);
} catch (IOException e) {
throw new HttpAccessException("IOException", e);
}
}
public static byte[] requestImg(String urlString, int width, int height) throws HttpAccessException {
try {
// logger.debug("Requesting: {}", urlString);
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("GET");
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
var inStream = connection.getInputStream();
var outStream = new ByteArrayOutputStream();
if (width > 0 & height > 0) {
try {
//压缩
Thumbnailator.createThumbnail(inStream, outStream, width, height);
inStream.close();
return outStream.toByteArray();
} catch (IOException ex) {
logger.warn("Thumbnailator error, url:", urlString, ex);
}
}
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
} else {
int code = connection.getResponseCode();
logger.error("Bad response code: {}", code);
throw new HttpAccessException("Bad response code: " + code);
}
} catch (MalformedURLException e) {
throw new HttpAccessException("Malformed url", e);
} catch (IOException e) {
throw new HttpAccessException("IOException", e);
}
}
public static byte[] postTryReadImg(String urlString, JsonNode body) throws HttpAccessException {
try {
// logger.debug("Requesting: {}", urlString);
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
if (body != null) {
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), charset);
logger.debug("Sending payload: {}", body);
writer.write(body.toString());
writer.close();
}
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
var inStream = connection.getInputStream();
var outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
} else {
int code = connection.getResponseCode();
logger.error("Bad response code: {}", code);
throw new HttpAccessException("Bad response code: " + code);
}
} catch (MalformedURLException e) {
throw new HttpAccessException("Malformed url", e);
} catch (IOException e) {
throw new HttpAccessException("IOException", e);
}
}
public static HttpPostMultipart buildMultiPartRequest(String requestURL, Map headers, String boundary) throws Exception {
return new HttpPostMultipart(requestURL, headers, boundary);
}
public static class HttpPostMultipart {
private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
// private String charset;
private OutputStream outputStream;
private PrintWriter writer;
/**
* 构造初始化 http 请求,content type设置为multipart/form-data
*/
private HttpPostMultipart(String requestURL, Map headers, String boundary) throws Exception {
// this.charset = charset;
if (StringUtil.isStringEmpty(boundary)) {
boundary = UUID.randomUUID().toString();
}
this.boundary = boundary;
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
if (headers != null && headers.size() > 0) {
Iterator it = headers.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
String value = headers.get(key);
httpConn.setRequestProperty(key, value);
}
}
outputStream = httpConn.getOutputStream();
// writer = new DataOutputStream(outputStream);
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true);
}
/**
* 添加form字段到请求
*/
public void addFormField(String name, String value) throws Exception {
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + name + "\"").append(LINE_FEED);
writer.append("Content-Type: text/plain; charset=" + charset).append(LINE_FEED);
writer.append(LINE_FEED);
writer.append(value).append(LINE_FEED);
// writer.write(sb.toString().getBytes());
writer.flush();
}
/**
* 添加文件
*/
public void addFilePart(String fieldName, String fileName, InputStream fileStream) throws Exception {
writer.append("--").append(boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"").append(fieldName).append("\"; filename=\"").append(fileName).append("\"").append(LINE_FEED);
writer.append("Content-Type: ").append(URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED);
// sb.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
// writer.write(sb.toString().getBytes());
writer.flush();
byte[] bufferOut = new byte[1024];
if (fileStream != null) {
int bytesRead = -1;
while ((bytesRead = fileStream.read(bufferOut)) != -1) {
outputStream.write(bufferOut, 0, bytesRead);
}
// while (fileStream.read(bufferOut) != -1) {
// writer.write(bufferOut);
// }
fileStream.close();
}
// outputStream.flush();
writer.append(LINE_FEED);
writer.flush();
}
/**
* Completes the request and receives response from the server.
*/
public JsonNode finish() throws Exception {
writer.flush();
writer.append("--").append(boundary).append("--").append(LINE_FEED);
// writer.write(("--" + boundary + "--" + LINE_FEED).getBytes());
writer.close();
// checks server's status code first
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
return JsonUtil.getObjectMapper().readTree(new InputStreamReader(httpConn.getInputStream()));
} else {
logger.error("Bad response code: {}", responseCode);
throw new HttpAccessException("Bad response code: " + responseCode);
}
}
}