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

boi*_*ter 1 java android content-length

我想通过request.getContentLength()服务器客户端JSP页面获取内容大小。但是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();
Run Code Online (Sandbox Code Playgroud)

Mat*_*tej 5

您正在使用conn.setChunkedStreamingMode(100),它将在预先未知content-lenght时有效地启用100字节块中的块传输编码

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