使用HttpURLConnection的getContentLength()方法返回-1??

当使用HttpURLConnection的getContentLength()方法获取数据长度时遇到返回-1的情况,原因在于服务器未设置'content-length'头。解决办法是确保服务器端设置HttpServletResponse的setContentLength或setContentLengthLong方法来指定内容长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天使用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(); //对应于HttpServletResponse.setContentLength(int)
        long length1 = conn.getContentLengthLong(); //对应于HttpServletResponse.setContentLengthLong(long)
        InputStream in = conn.getInputStream();
        ReadableByteChannel srcChannel = Channels.newChannel(in);

        //将网络通道中的数据写入到本地文件中
        File file = new File("out.txt");
        FileOutputStream fout = new FileOutputStream(file);
        FileChannel dstChannel = fout.getChannel();
        dstChannel.transferFrom(srcChannel, 0, length1);

        //释放资源
        dstChannel.close();
        fout.close();
        srcChannel.close();
        in.close();
        conn.disconnect();
    }
}

server:

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Demo01
 */
@WebServlet("/demo01")
public class Demo01 extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public Demo01() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        File file = new File("aa.txt");

        File file1 = new File(getServletContext().getRealPath("/files/test.txt"));
        if(file1.exists()) {
            System.out.println("exists ......");
        }

        ServletOutputStream out = response.getOutputStream();
        /* 客户端获取传输数据长度
        conn.getContentLength();
        conn.getContentLengthLong();
        */

        // response.setContentLength((int)file1.length()); //对应于HttpURLConnection.getContentLength()
        response.setContentLengthLong(file1.length()); //对应于HttpURLConnection.getContentLengthLong()

        FileChannel channel = new FileInputStream(file1).getChannel();
        channel.transferTo(0, file1.length(), Channels.newChannel(out));

        channel.close();
        out.close();
    }
}




评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值