今天使用HttpURLConnection类的getContentLength()方法时得到-1, 这是为什么呢??
是这样的, 用HttpURLConnection的getContentLength获取传输数据的字节数时, 必须与服务器端协商, 即服务器端必须设置过"content-length"头:
HttpURLConnection.getContentLength()方法对应于服务端的的HttpServletResponse.setContentLength(int)
HttpURLConnection.getContentLengthLong()方法对应于服务端的HttpServletResponse.setContentLengthLong(long)
如果服务端没有设置Content-Longth, 那么客户端获取Content-Length时就是-1
下面是client和server端的相关代码:
client:
public class Demo2 {
public static void main(String[] argv) throws IOException {
URL url = new URL("http://127.0.0.1:8080/webserver01/demo01");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//关于下面一句, 参考: http://my.oschina.net/u/133352/blog/96582
conn .setRequestProperty("Accept-Encoding", "identity");
conn.connect();
//必须要服务器的HttpServletResponse.setContentLength(int), 否则下面的getContentLength()将返回-1
int length = conn.getContentLength(); </