How to store an Http Response that may contain binary data?

前端 未结 5 1730
情话喂你
情话喂你 2020-12-31 19:03

As I described in a previous question, I have an assignment to write a proxy server. It partially works now, but I still have a problem with handling of gzipped information.

5条回答
  •  长发绾君心
    2020-12-31 19:30

    Jersey — a high level web framework — may save your day. You don't have to manage gzip content, header, etc, yourself anymore.

    The following code gets the image used for your example and save it to disk. Then it verifies the saved image is equal to the downloaded one:

    import com.google.common.io.ByteStreams;
    import com.google.common.io.Files;
    import com.sun.jersey.api.client.Client;
    import com.sun.jersey.api.client.ClientResponse;
    
    @Test
    public void test() throws IOException {
        String filename = "ps_logo2.png";
        String url = "http://www.google.com/images/logos/" + filename;
        File file = new File(filename);
    
        WebResource resource = Client.create().resource(url);
        ClientResponse response = resource.get(ClientResponse.class);
        InputStream stream = response.getEntityInputStream();
        byte[] bytes = ByteStreams.toByteArray(stream);
        Files.write(bytes, file);
    
        assertArrayEquals(bytes, Files.toByteArray(file));
    }
    

    You will need two maven dependencies to run it:

    
        com.sun.jersey
        jersey-client
        1.6
    
    
        com.google.guava
        guava
        r08
    
    

提交回复
热议问题