Servlet 3.0从android读取gzip为multipart

时间:2013-01-31 16:16:45

标签: android gzip multipart servlet-3.0

如果数据是作为gzip发送的,如何将发送到服务器的数据直接读入部分? 这是将文件上传到服务器的基本android代码

private void sendViaUrlConnection(String urlPost,
        ArrayList<BasicNameValuePair> pairList, File[] sentfileList) {
    HttpURLConnection connection = null;
    GZIPOutputStream gz = null;
    DataOutputStream outputStream = null;
    OutputStream serverOutputStream = null;
    try {
        URL url = new URL(urlPost);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("User-Agent",
            "Android Multipart HTTP Client 1.0");
        connection.setRequestProperty("Content-Type",
            "multipart/form-data; boundary=" + boundary);
        connection.setRequestProperty("accept-encoding", "gzip,deflate");
        connection.setRequestProperty("accept","text/html,application/xhtml"
                    + "+xml,application/xml;q=0.9,*/*;q=0.8");
        if (isServerGzip) {
            connection.setRequestProperty("Content-Encoding", "gzip");
            gz = new GZIPOutputStream(connection.getOutputStream());
            serverOutputStream = gz;
        } else {
            outputStream = new DataOutputStream(
                    connection.getOutputStream());
            serverOutputStream = outputStream;
        }
        getMultiPartData(pairList, sentfileList, serverOutputStream,
            boundary);
        serverResponseCode = connection.getResponseCode();
    } finally {}
}  

如果isServerGzip为false,则servlet获取数据正常但如果我尝试发送GZIPOutputStream,则servlet中的getParts()函数返回一个空列表。 这是servlet的代码:

@WebServlet("/AddInfo.jsp")
@MultipartConfig()
public class AddInfo extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        Collection<Part> parts = request.getParts();
        for (Part part : parts) {
            // Do something with each part
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我怀疑(在看到你的getMultiPartData()之前无法确定)你传递给GZIPOutputStream多部分标题 - 例如:

writer.append("--" + boundary).append(CRLF);
writer.append(
        "Content-Disposition: form-data; name=\"binaryFile\"; filename=\""
            + file.getName() + "\"").append(CRLF);
writer.append(
        "Content-Type: "
            + ((isServerGzip) ? "application/gzip" : URLConnection
                    .guessContentTypeFromName(file.getName())))
            .append(CRLF);

请参阅here

有关设法发送数据的类,请参阅我的问题here。请注意,我将连接的输出流包装在GZIPOutputStream中,但是我没有在GZIPOutputStream中编写多部分头。