Java以post请求发送文件或json数据
分别给出了post发送文件和json数据的函数,其中使用到了Jackson库来转化Json数据,使用log4j2来打印日记,可自行剔除。
public class HttpUtils {static private ObjectMapper objectMapper=new ObjectMapper();static private Logger logger= LogManager.getLogger();/*** 以post请求方式发送文件* @param url * @param name 文件的请求参数名* @param fileName 文件名* @param fileInput 文件的输入流* @return 默认返回参数为Json格式的数据* @throws IOException* @throws InterruptedException*/static public Map<String,Object> postFile2(String url,String name,String fileName,InputStream fileInput) throws IOException, InterruptedException {String charset = "UTF-8";String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.String CRLF = "\r\n"; // Line separator required by multipart/form-data.URLConnection connection = new URL(url).openConnection();connection.setDoOutput(true);connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);try (OutputStream output = connection.getOutputStream();PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);) {// Send binary file.writer.append("--" + boundary).append(CRLF);writer.append("Content-Disposition: form-data; name=\""+URLEncoder.encode(name,"UTF-8")+"\"; filename=\"" + URLEncoder.encode(fileName,"UTF-8") + "\"").append(CRLF);writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)).append(CRLF);writer.append("Content-Transfer-Encoding: binary").append(CRLF);writer.append(CRLF).flush();fileInput.transferTo(output);output.flush(); // Important before continuing with writer!writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.// End of multipart/form-data.writer.append("--" + boundary + "--").append(CRLF).flush();}// Request is lazily fired whenever you need to obtain information about response.int responseCode = ((HttpURLConnection) connection).getResponseCode();System.out.println(responseCode); // Should be 200//读取响应消息BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream()));StringBuilder stringBuilder=new StringBuilder();String tempStr=null;while((tempStr=reader.readLine())!=null){stringBuilder.append(tempStr);}//转化为JSONMap<String,Object> response= objectMapper.readValue(stringBuilder.toString(),Map.class);return response;}/*** 以post请求发送Json文件*/public static Map<String,Object> sendJsonPost(String url,String jsonStr) throws IOException, Utils.ReceiveBadCodeException {HttpURLConnection httpURLConnection= (HttpURLConnection) new URL(url).openConnection();//配置连接httpURLConnection.setDoOutput(true);httpURLConnection.setRequestMethod("POST");httpURLConnection.setRequestProperty("Content-Type","application/json;charset=UTF-8");OutputStream out=httpURLConnection.getOutputStream();//发送out.write(jsonStr.getBytes("UTF-8"));//检查响应InputStream in=httpURLConnection.getInputStream();StringBuilder stringBuilder=new StringBuilder();byte[] bytes=new byte[1024];int num;while((num=in.read(bytes))!=-1){stringBuilder.append(new String(bytes,"utf-8"));}Map<String,Object> response=objectMapper.readValue(stringBuilder.toString(),Map.class);return response;}}
参考:
- Upload files from Java client to a HTTP server
- Sending HTTP POST Request In Java
Java以post请求发送文件或json数据相关推荐
- java发送post请求上传文件和json数据
java发送post请求上传文件和json数据 因为第三方的上传服务post参数使用了两个@requestpart参数. 但是feign不可以使用两个@requestpart参数.会报错:java.l ...
- php curl form-data,在php curl multipart / form-data请求中发送一个文件和json数据
我正在尝试在PHP的curl请求中上传文件和json数据 . 请求在命令行中使用curl正常工作 . 这是命令行中的curl请求: curl -v --basic -u'username' -F fi ...
- nodejs爬虫,POST请求发送Request Playload格式数据
nodejs爬虫,POST请求发送Request Playload格式数据. 本文以网易云课堂其中2个POST请求为例,使用request模块实现. 例子1 1.地址: http://study.16 ...
- Java 和 Python 解析动态 key 的 JSON 数据
一.概述 解析JSON过程中,什么情况都可能遇到.遇到特殊的情况,不会怎么办?肯定不是设计的问题,一定是你的姿势不对. 有这样一种JSON需要解析: {"b3444533f6544" ...
- Java发起post请求并以FormData携带数据
Java发起post请求并以FormData携带数据 List<NameValuePair> body = new ArrayList<>(); body.add(new Ba ...
- UnityWebRequest.Post 发送和接收Json数据
1.C#:发送和接收Json数据 using UnityEngine; using UnityEngine.Networking; using System.Collections; using Un ...
- java 控制器 返回 json_SpringMVC中controller返回json数据的方法
java 控制器 返回 json_SpringMVC中controller返回json数据的方法 1.方法一: 使用springmvc原生注解@ResponseBody @ResponseBody @ ...
- RestTemplate POST请求发送文件
上次说了RestTemplate的基本用法,包括简单的GET和POST请求,但都是普通类型的字段.这次说说参数是文件类型的POST请求发送方法. RestTemplate上传文件 1. 服务端 2. ...
- java 电脑向手机发送文件
一.手机向手机发送文件 1.这里需要一个jar包:bluecove.jar 项目里也会有带在lib里 2. 寻找蓝牙设备: private void searchButtonActionPerform ...
最新文章
- mono+jexus 部署之CompilationException
- 第02章_MySQL环境搭建
- python做动态折线图_Python数据可视化 pyecharts实现各种统计图表过程详解
- idea ctrl+shift+f快捷键失效
- ipad能安装python么_ipad能下载python么
- JS实现全选、反选、不选
- 阿里大数据分析与应用(part5)--QuickBI
- 关于Java 8的Optional的介绍
- CloudStack 配置高级网络简明手册
- php 生成图片 打印,php 生成水印图片
- Docker 构建 redis 集群
- lnmp的php.ini,lamp/lnmp优化3--phpini
- Jquery-数组删除元素
- jquery 选择器 逗号
- 过滤字符串 和 select选择后控件值变更
- 这些 Google 高级搜索技巧,你都知道么?
- 分分钟免费搭建一个简单而美博客
- Java Reflection
- 拿棱镜门黑客软件攻击“俄版百度”,不偷情报只想装大V,FBI们被抓包了
- 打造企业级云深度学习平台——小米云深度学习平台的架构设计与实现