如何在android中设置内容长度?

时间:2012-04-12 10:20:13

标签: java android content-length

我想在服务器客户端JSP页面中通过request.getContentLength()获取内容大小。 但是request.getContentLength()总是返回-1,我不知道为什么?

Android代码段代码:

URL uri = new URL(actionUrl);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
//conn.setChunkedStreamingMode(100);
conn.setConnectTimeout(setTimeOut>0?setTimeOut:timeoutConnection);
conn.setReadTimeout(setTimeOut>0?setTimeOut:timeoutConnection);  
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "keep-alive");

//conn.setRequestProperty("content-length", "10");
//conn.addRequestProperty("content-length", "20");
conn.setFixedLengthStreamingMode(30);

conn.setRequestProperty("Charsert", ENCODING);
conn.setRequestProperty("Content-Type", "multipart/form-data"
                + ";boundary=" + java.util.UUID.randomUUID().toString());
conn.connect();

1 个答案:

答案 0 :(得分:4)

您正在使用conn.setChunkedStreamingMode(100),当内容长度事先未知时,它将有效地启用100个字节块中的chunked transfer encoding

如果您事先知道要在请求正文中发送的内容的长度,请使用conn.setFixedLengthStreamingMode(int len)