Java中通过流获取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;
}

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

猜你喜欢

转载自blog.csdn.net/D578332749/article/details/80760198