当前位置: 首页 > news >正文

HttpURLConnection发送各种内容格式

通过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);

 自定义一些header

public static JsonNode getResponseWithHeaders(String urlString, Map<String, String> 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);}}

get/post application/json 并接收application/json

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> T postReadClassResponse(String urlString, Object body, Class<T> 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);}}

post application/x-www-form-urlencoded

public static String postApplicationFormUrlencoded(String urlString, Map<String, Object> 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);}}

post application/json 并接收byte array

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);}}

post multipart/form-data 并接收json

public static HttpPostMultipart buildMultiPartRequest(String requestURL, Map<String, String> 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<String, String> 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 methodhttpConn.setDoInput(true);httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);if (headers != null && headers.size() > 0) {Iterator<String> 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 firstint 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);}}}

http://www.lryc.cn/news/267545.html

相关文章:

  • 摇杆控制人物移动
  • Jenkins自动化部署之后端
  • Could not resolve com.github.CymChad:BaseRecyclerViewAdapterHelper:2.9.28.
  • RK3588平台开发系列讲解(AI 篇)RKNN rknn_query函数详细说明
  • 15个主流设计灵感网站,激发你的创作灵感!
  • Matlab:解非线性方程组
  • 面向 AI,重塑云基础设施、存储、芯片、Serverless……2023亚马逊云科技re:Invent中国行
  • 【JDK新特性】JDK和Springboot各版本新特性介绍
  • tomcat剖析:开篇
  • 华为路由器:DHCP配置
  • (企业 / 公司项目)微服务OpenFeign怎么实现服务间调用?(含面试题)
  • 数据结构:图文详解 树与二叉树(树与二叉树的概念和性质,存储,遍历)
  • DM工作笔记-在windows下对DM7进行库还原恢复
  • STM32软硬件CRC测速对比
  • 第九部分 图论
  • 如何用java实现对java虚拟机的性能监控?
  • 电路设计(7)——窗口比较器的multism仿真
  • 前端已死?探讨人工智能与低代码对前端的影响
  • 树莓派,opencv,Picamera2利用舵机云台追踪人脸(PID控制)
  • uniapp中推出当前微信小程序
  • AndroidStudio无法新建aidl文件解决办法
  • java爬虫(jsoup)如何设置HTTP代理ip爬数据
  • ZooKeeper Client API 安装及使用指北
  • 本机ping不通虚拟机
  • Linux cfdisk命令
  • 实用学习网站和资料
  • 【已解决】c++qt如何制作翻译供程序调用
  • DPDK单步跟踪(3)-如何利用visual studio 2019和visual gdb来单步调试dpdk
  • Python爬虫---解析---BeautifulSoup
  • Argument list too long when copying files