Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/185.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java HttpURLConnection显示进度_Java_Android_Http - Fatal编程技术网

Java HttpURLConnection显示进度

Java HttpURLConnection显示进度,java,android,http,Java,Android,Http,我使用HttpURLConnection连接我的服务器。我想显示更新进程 URL url = new URL(RequestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.set...// many params. DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); dos.write("http Str

我使用HttpURLConnection连接我的服务器。我想显示更新进程

URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.set...// many params.
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.write("http String"); // eg Content-Disposition: form-data......
InputStream is = new FileInputStream(file); // Take file to Stream.
while(){
   dos.write(fileString);// Take file Strean to memory.This place can take prograss,but just in momory,not post to server proress.
}
dos.flush();
InputStream input = conn.getInputStream(); // This place will post data to server,but i donot how to get progress.
请帮助我,谢谢。

你可以用它。

是不推荐的,因为API 30

我使用getContentLength并从流中读取固定块,设法从HttpURLConnection中获得进展。如果服务器不包含Content-Length标头,则必须找到另一种方法来获取要下载的总数据大小

下面的代码段显示了报告下载进度的示例:

try {
        URL url = new URL(theURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept-Encoding", "identity");
        
        InputStream is = new BufferedInputStream(conn.getInputStream());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        long totalLength = conn.getContentLengthLong();
        int resultLength;
        byte[] buffer = new byte[512];
        while ((resultLength = is.read(buffer)) != -1) {
            baos.write(buffer, 0, resultLength);

            if (totalLength > 0)
                // Report the progress using baos.size() and totalLength
        }
    } catch (Exception ex){
        // Deal with that
    }
您可以用OutputStreamWriter替换为teArrayoutPutStream,因为数据不是二进制的