如何发送压缩的http请求?

时间:2012-10-03 11:13:03

标签: java web-services zip http-post

我想发送一个压缩的请求正文作为基于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 个答案:

答案 0 :(得分:5)

HTTP协议不支持压缩请求(它支持在客户端宣布其处理压缩内容的能力的情况下交换压缩响应)。如果要实现压缩请求,则应在客户端和Web服务之间建立这样的协议,以便始终压缩HTTP有效负载,以便在接收端,Web服务始终可以解压缩并解释有效负载。

答案 1 :(得分: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 {

    }
}

答案 2 :(得分: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;
}

}