当前位置: 首页 > 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);}}}

相关文章:

  • mysql怎么只允许指定IP访问
  • 书生·浦语大模型实战营——两周带你玩转微调部署评测全链路
  • Jenkins的邮箱配置和插件下载
  • PHP数组定义和输出
  • 【深度学习-目标检测】03 - Faster R-CNN 论文学习与总结
  • Laravel框架使用phpstudy本地安装的composer用Laravel 安装器进行安装搭建
  • 【操作系统】探究进程奥秘:显示进程列表的解密与实战
  • 前端性能优化三十一:花裤衩模板webpack DllPlugin
  • 【JVM】虚拟机栈与本地方法栈
  • redis—String字符串
  • 【unity学习笔记】3.常用结构体
  • MyBatis——MyBatis的缓存
  • TrustZone之与非安全虚拟化交互
  • docker-compose 安装Sonar并集成gitlab
  • 构造LR(1)分析表和LALR(1)分析表
  • 【译】理解JavaScript:new 关键字
  • classpath对获取配置文件的影响
  • CODING 缺陷管理功能正式开始公测
  • Elasticsearch 参考指南(升级前重新索引)
  • exif信息对照
  • Flex布局到底解决了什么问题
  • iBatis和MyBatis在使用ResultMap对应关系时的区别
  • javascript从右向左截取指定位数字符的3种方法
  • Js实现点击查看全文(类似今日头条、知乎日报效果)
  • Koa2 之文件上传下载
  • magento2项目上线注意事项
  • SpriteKit 技巧之添加背景图片
  • Vue2.0 实现互斥
  • XForms - 更强大的Form
  • 复杂数据处理
  • 马上搞懂 GeoJSON
  • 排序(1):冒泡排序
  • 适配iPhoneX、iPhoneXs、iPhoneXs Max、iPhoneXr 屏幕尺寸及安全区域
  • 正则表达式
  • hi-nginx-1.3.4编译安装
  • 阿里云移动端播放器高级功能介绍
  • #我与Java虚拟机的故事#连载04:一本让自己没面子的书
  • %3cscript放入php,跟bWAPP学WEB安全(PHP代码)--XSS跨站脚本攻击
  • (4)(4.6) Triducer
  • (ctrl.obj) : error LNK2038: 检测到“RuntimeLibrary”的不匹配项: 值“MDd_DynamicDebug”不匹配值“
  • (八)c52学习之旅-中断实验
  • (多级缓存)缓存同步
  • (十一)c52学习之旅-动态数码管
  • (四)linux文件内容查看
  • (原創) 是否该学PetShop将Model和BLL分开? (.NET) (N-Tier) (PetShop) (OO)
  • (源码版)2024美国大学生数学建模E题财产保险的可持续模型详解思路+具体代码季节性时序预测SARIMA天气预测建模
  • (转)树状数组
  • *_zh_CN.properties 国际化资源文件 struts 防乱码等
  • .NET 同步与异步 之 原子操作和自旋锁(Interlocked、SpinLock)(九)
  • .net 验证控件和javaScript的冲突问题
  • .net实现客户区延伸至至非客户区
  • @AutoConfigurationPackage的使用
  • @PreAuthorize注解
  • [ C++ ] STL---string类的使用指南
  • []我的函数库