如果数据是作为 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
}
}
}