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")
4

3 回答 3

5

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

于 2012-10-03T11:17:44.907 回答
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;
}

}

于 2014-03-20T15:28:19.280 回答
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 {

    }
}
于 2012-10-08T13:57:30.203 回答