用于解密 GZIP 正文的 Rest Api

一个API以GZIP的形式在正文中发送大量数据,我需要创建 rest API 来解密并将其保存在数据库中,但我无法解密数据。


`@GetMapping

    public void hello() throws IOException {

        String payload = "{\n" +

                "    \"name1\": \"shrikant\",\n" +

                "    \"date\": \"Fri Apr 05 15:48:59 IST 2019\"\n" +

                "}";

        String urlStr = "http://localhost:8080/hello";

        URL url = new URL(urlStr);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setReadTimeout(60000);

        conn.setConnectTimeout(60000);

        conn.setRequestMethod("POST");

        conn.setDoInput(true);

        conn.setDoOutput(true);

        conn.setRequestProperty("Accept", "application/json");

        conn.setRequestProperty("Content-Type", "application/json");

        conn.addRequestProperty("Content-Encoding", "gzip");

        OutputStream os = conn.getOutputStream();

        GZIPOutputStream gos = new GZIPOutputStream(os);

        gos.write(payload.getBytes(StandardCharsets.UTF_8));

        System.out.println("payload " + 

        Arrays.toString(payload.getBytes(StandardCharsets.UTF_8)));

        os.close();

        int responseCode = conn.getResponseCode();

    System.out.println("\nSending 'POST' request to URL : " + url);

    System.out.println("Response Code : " + responseCode);

    }`

用于接收数据的 API。


     @PostMapping("hello")

    public byte[] hello1(HttpServletRequest request) throws IOException {

        System.out.println("hi");

        ByteArrayInputStream bis = new ByteArrayInputStream();

        GZIPInputStream gis = new GZIPInputStream(bis);

        BufferedReader br = new BufferedReader(new InputStreamReader(gis, "UTF-8"));

        StringBuilder sb = new StringBuilder();

        String line;

        while((line = br.readLine()) != null) {

            sb.append(line);

        }

    }

但无法解密数据。


如何解密请求。


慕姐4208626
浏览 124回答 1
1回答

萧十郎

在客户端,您应该在关闭输出流之前关闭 GZIP 输出流。    gos.close();    os.close();在服务器端,您应该使用来自请求的输入流    ServletInputStream inputStream = request.getInputStream();    GZIPInputStream gis = new GZIPInputStream(inputStream);    BufferedReader br = new BufferedReader(new InputStreamReader(gis, "UTF-8"));    StringBuilder sb = new StringBuilder();    String line;    while((line = br.readLine()) != null) {        sb.append(line);    }    System.out.println(sb.toString());对于流,最好使用尝试资源blok,您不必记住关闭流。    try (OutputStream os = conn.getOutputStream()) {        try (GZIPOutputStream gos = new GZIPOutputStream(os)) {            gos.write(payload.getBytes(StandardCharsets.UTF_8));        }    }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java