博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java中通过流获取http请求体中的数据
阅读量:2058 次
发布时间:2019-04-29

本文共 2306 字,大约阅读时间需要 7 分钟。

最近一个项目需要在http传输过程中进行数据加密,则需要通过流来读写http请求的包体内容,结果发现在接收方获取到的流数据是空的,最后发现是因为没有设置请求数据内容类型的缘故,即此行代码:

conn.setRequestProperty("content-type", "text/html");

以下展示整个基于java的http请求的发起和接收

  • http请求代码
public String httpRequest(String requestUrl, String requestMethod, Map
requestParameters) throws IOException { try { URL url = new URL(requestUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true);//需要用到输出流 conn.setDoInput(true);//需要用到输入流 conn.setRequestMethod(requestMethod); conn.setRequestProperty("content-type", "text/html");//设置内容类型 // 使用输出流添加数据至请求体 if (requestParameters.size() != 0) { String json = Context.gson.toJson(requestParameters);//转换为json OutputStream os = conn.getOutputStream();//获取输出流 os.write(json.getBytes());//写入 os.flush(); } conn.connect(); // 读取服务器端返回的内容 InputStream is = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(is, "utf-8"); BufferedReader br = new BufferedReader(isr); StringBuffer buffer = new StringBuffer(); String line; while ((line = br.readLine()) != null) { buffer.append(line); } return buffer.toString(); } catch (Exception e) { logger.error("http请求异常", e); throw e; }}
  • http请求接收处理,此处可以使用字符流,此处使用字节流是因为我的数据是使用字节传递的
public String activate(){    InputStream is = null;    try {        is = request.getInputStream();//获取输入流        ArrayList
arr = new ArrayList
(); byte[] buffer = new byte[50];//缓存数组 int len; //读取数据 while ((len=is.read(buffer))!=-1) { for (int i = 0; i < len; i++) { arr.add(buffer[i]); } } byte[] src = new byte[arr.size()]; for (int i = 0; i < src.length; i++) { src[i] = arr.get(i); } String json = new String(src); @SuppressWarnings("unchecked") Map
map = Context.gson.fromJson(json, HashMap.class); System.out.println(map); } catch (Exception e) { e.printStackTrace(); } finally { if (is != null) is.close(); } return SUCCESS;}

要对传输的数据进行加密,则只需要在写入和读取的位置对数据进行加密即可

转载地址:http://ovtlf.baihongyu.com/

你可能感兴趣的文章
剑指offer 21.包含min函数的栈
查看>>
剑指offer 23.从上往下打印二叉树
查看>>
剑指offer 25.二叉树中和为某一值的路径
查看>>
剑指offer 26. 数组中出现次数超过一半的数字
查看>>
剑指offer 27.二叉树的深度
查看>>
剑指offer 29.字符串的排列
查看>>
剑指offer 31.最小的k个树
查看>>
剑指offer 32.整数中1出现的次数
查看>>
剑指offer 33.第一个只出现一次的字符
查看>>
剑指offer 34.把数组排成最小的数
查看>>
剑指offer 35.数组中只出现一次的数字
查看>>
剑指offer 36.数字在排序数组中出现的次数
查看>>
剑指offer 37.数组中重复的数字
查看>>
剑指offer 38.丑数
查看>>
剑指offer 39.构建乘积数组
查看>>
剑指offer 57. 删除链表中重复的结点
查看>>
剑指offer 58. 链表中环的入口结点
查看>>
剑指offer 59. 把字符串转换成整数
查看>>
剑指offer 60. 不用加减乘除做加法
查看>>
leetcode 热题 Hot 100-3. 合并两个有序链表
查看>>