1、在做微信支付结果通知的时候,看到一个描述:微信会把相关支付结果及用户信息通过数据流的形式发送给商户 ,那么java如何通过数据流的形式发送数据呢?
public static String doPostFileStreamAndJsonObj(String url , String json) {String result = "";// 请求返回参数try {URL u = new URL(url);HttpURLConnection conn = (HttpURLConnection) u.openConnection();conn.setDoOutput(true);conn.setDoInput(true);conn.setUseCaches(false);conn.setRequestMethod("POST");conn.setRequestProperty("connection", "Keep-Alive");conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.72 Safari/537.36");conn.setRequestProperty("Charsert", "UTF-8");// 这里的content-type 设置为json格式 --- 否则不能传输数据conn.setRequestProperty("Content-Type", "application/json");conn.setChunkedStreamingMode(10240000);// 定义输出流,有什么数据要发送的,直接后面append就可以,记得转成byte再appendOutputStream out = new DataOutputStream(conn.getOutputStream());byte[] end_data = json.getBytes(Charset.defaultCharset());// 定义最后数据分隔线// 发送流out.write(end_data);out.flush();out.close();// 定义BufferedReader输入流来读取URL的响应BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));String line = "";while ((line = reader.readLine()) != null) {result += line;}} catch (Exception e) {System.out.println("发送POST请求出现异常!" + e);e.printStackTrace();}return result;}
@RequestMapping("/req/stream")
public String req(HttpServletRequest request) throws IOException {final StringBuffer sb = new StringBuffer();BufferedReader reader = request.getReader();String line ;while((line= reader.readLine())!= null) {sb.append(line);}System.out.println("获取到结果是===>>>" + sb.toString());return sb.toString();
}
@Test
public void testStream () throws Exception{String url = "http://localhost:8080/httpStream/req/stream";Map data = new HashMap();data.put("id", "123");data.put("name", "王二狗");String doPost = HttpStreamUtil.doPostFileStreamAndJsonObj(url, JsonMapper.toJsonString(data));System.out.println(doPost);System.out.println("执行结束》。。");
}
1、只要以 post - json的方式提交数据,即可使用 request.getReader(); 方式,获取数据。
Content-Type:application/json
--- postman 相关文章学习
https://thinkcode.blog.csdn.net/article/details/83114474
https://thinkcode.blog.csdn.net/article/details/115366637
https://thinkcode.blog.csdn.net/article/details/116454823
--- 微信支付相关文章
https://thinkcode.blog.csdn.net/article/details/110948517
https://thinkcode.blog.csdn.net/article/details/110927389
https://thinkcode.blog.csdn.net/article/details/109074212
https://thinkcode.blog.csdn.net/article/details/109028220
https://thinkcode.blog.csdn.net/article/details/88998211