Java中通过流获取http请求体中的数据

本文介绍了一个基于Java的HTTP请求加密传输案例,详细展示了如何通过设置请求头中的Content-Type来正确发送HTTP请求,并提供了完整的发送与接收端代码实现。

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

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

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

  • http请求代码
public String httpRequest(String requestUrl, String requestMethod, Map<String, String> 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<Byte> arr = new ArrayList<Byte>();
        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<String, Object> map = Context.gson.fromJson(json, HashMap.class);
        System.out.println(map);
    }  catch (Exception e) {
        e.printStackTrace();
    }  finally {
        if (is != null)
            is.close();
    }
    return SUCCESS;
}

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

评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值