如何发送压缩的HTTP请求?

4
我想发送一个压缩过的请求体作为基于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")
3个回答

5

HTTP协议不支持压缩请求(它支持交换压缩响应,客户端会宣告它有能力处理压缩内容)。如果您想要实现压缩请求,那么应该在客户端和您的Web服务之间建立这样的协议,即始终压缩HTTP载荷,使得在接收端,Web服务可以始终解压并解读载荷。


1
我能够解决这个问题,我们可以发送压缩的HTTP POST请求。需要使用Apache HTTPClient来实现。您能告诉我如何在此处附加参考代码吗? - nilman
HttpURLConnection请求 = null; StringBuilder sb = new StringBuilder(getFileAsString("TestFile.txt")); String fileStr = getFileAsString("TestFile.txt"); HttpClient客户端 = new HttpClient(); client.getState().setCredentials(new AuthScope(hostip, port), new UsernamePasswordCredentials("username", "password")); PutMethod方法 = new PutMethod(url); post.setRequestHeader("Content-Encoding", "gzip"); - nilman

0
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 {

    }
}

0

我使用一个特殊的servlet来解压缩请求和响应

public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException{

    InputStream zipedStreamRequest = req.getInputStream();
    String unzipJsonStr  = ZipUtil.uncompressWrite(zipedStreamRequest);
    System.out.println("<---- ZIP request <----");
    System.out.println(unzipJsonStr);
    MainHandler handler = new MainHandler();
    String responseJson = handler.handle(unzipJsonStr);
    System.out.println("----> ZIP response ---->");
    System.out.println(responseJson);

    OutputStream responseOutputStream = res.getOutputStream();

    if (responseJson!=null) {
        ZipUtil.compressWrite(responseJson, responseOutputStream);  
    }

}

那么这是我的ziputil类

public class ZipUtil {

private static final int NB_BYTE_BLOCK = 1024;

/**
 * compress and write in into out
 * @param in the stream to be ziped
 * @param out the stream where to write
 * @throws IOException if a read or write problem occurs
 */
private static void compressWrite(InputStream in, OutputStream out) throws IOException{
    DeflaterOutputStream deflaterOutput = new DeflaterOutputStream(out);
    int nBytesRead = 1;
    byte[] cur = new byte[NB_BYTE_BLOCK];
    while (nBytesRead>=0){
        nBytesRead = in.read(cur);
        byte[] curResized;
        if (nBytesRead>0){
            if (nBytesRead<NB_BYTE_BLOCK){
                curResized = new byte[nBytesRead];
                System.arraycopy(cur, 0, curResized, 0, nBytesRead);
            } else {
                curResized = cur;
            }
            deflaterOutput.write(curResized);
        }

    }
    deflaterOutput.close();
}

/**
 * compress and write the string content into out
 * @param in a string, compatible with UTF8 encoding
 * @param out an output stream
 */
public static void compressWrite(String in, OutputStream out){
    InputStream streamToZip = null;
    try {
        streamToZip = new ByteArrayInputStream(in.getBytes("UTF-8"));           
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    try {
        ZipUtil.compressWrite(streamToZip, out);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

/**
 * uncompress and write int into out
 * @param in
 * @param out
 * @throws IOException
 */
private static void uncompressWrite(InputStream in, OutputStream out) throws IOException{
    InflaterInputStream inflaterInputStream = new InflaterInputStream(in);
    int nBytesRead = 1;
    byte[] cur = new byte[NB_BYTE_BLOCK];
    while (nBytesRead>=0){
        nBytesRead = inflaterInputStream.read(cur);
        byte[] curResized;
        if (nBytesRead>0){
            if (0<=nBytesRead && nBytesRead<NB_BYTE_BLOCK){
                curResized = new byte[nBytesRead];
                System.arraycopy(cur, 0, curResized, 0, nBytesRead);
            } else {
                curResized = cur;
            }
            out.write(curResized);
        }
    }

    out.close();
}

/**
 * uncompress and write in into a new string that is returned
 * @param in
 * @return the string represented the unziped input stream
 */
public static String uncompressWrite(InputStream in){
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        uncompressWrite(in, bos);
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    try {
        byte[] byteArr = bos.toByteArray();
        String out = new String(byteArr, "UTF-8");
        return out;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    return null;
}

}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接