有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何发送压缩的http请求?

我想发送一个压缩的请求主体,作为基于web服务的应用程序的POST http请求。有谁能帮我发送一个压缩的http请求,或者作为POST http请求的一部分发送一个压缩的请求正文

编辑在此处添加解决方案

HttpURLConnection request = null; 
StringBuilder sb = new StringBuilder(getFileAsString("TestFile.txt")); 
String fileStr = getFileAsString("TestFile.txt"); 
HttpClient client = new HttpClient(); 
client.getState().setCredentials(
    new AuthScope(hostip, port), 
    new UsernamePasswordCredentials("username", "password")); 
PutMethod post = new PutMethod(url); 
post.setRequestHeader("Content-Encoding", "gzip")

共 (2) 个答案

  1. # 1 楼答案

    public static void main(String[] args) throws MessagingException,
            IOException {
    
        HttpURLConnection request = null;
        try {
    
            // Get the object of DataInputStream
            StringBuilder sb = new StringBuilder(getFileAsString("TestFile.txt"));
    
            String fileStr = getFileAsString("TestFile.txt");
    
            System.out.println("FileData=" + sb);
            HttpClient client = new HttpClient();
              client.getState().setCredentials(
                        new AuthScope(hostip, portno),
                        new UsernamePasswordCredentials(username, password));
    
            PutMethod post = new PutMethod(url);
            post.setRequestHeader("Content-Encoding", "gzip");
            post.setRequestHeader("Content-Type", "application/json");
    
            post.setDoAuthentication(true);
    
            byte b[] = getZippedString(fileStr);;
                InputStream bais = new ByteArrayInputStream(b);
            post.setRequestBody(bais);
            try {
                int status = client.executeMethod(post);
    
            } finally {
                // release any connection resources used by the method
                post.releaseConnection();
            }
    
        }catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
    
        }
    }
    
  2. # 2 楼答案

    HTTP协议不支持压缩请求(它支持在客户端宣布其处理压缩内容的能力时交换的压缩响应)。如果您想要实现压缩请求,那么应该在客户端和web服务之间建立这样一个协议,HTTP负载总是被压缩的,这样在接收端,web服务总是可以解压和解释负载