java Android HttpUrlConnection 如何将响应读成碎片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7833219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:37:23  来源:igfitidea点击:

Android HttpUrlConnection how to read response into pieces

javaandroidresponsehttpurlconnection

提问by Android-Droid

actually I need a little more information about how to read response from HttpUrlConnectionclass in Android SDK. I'm trying to read a response from web server,but when it's too big my applications is throwin an OutOfMemoryException. So any source/help/suggestions on how to read the whole response into pieces is welcomed.

实际上,我需要更多有关如何从HttpUrlConnectionAndroid SDK 中的类读取响应的信息。我正在尝试从 Web 服务器读取响应,但是当它太大时,我的应用程序会抛出一个OutOfMemoryException. 因此,欢迎任何关于如何将整个回复阅读成碎片的来源/帮助/建议。

As I made a research I found out that I should set something like this : ((HttpURLConnection) connection).setChunkedStreamingMode(1024);But my problem is that I don't know how to read this chuncked stream. So I'll be very happy if someone can guide me through the right way.

当我进行研究时,我发现我应该设置如下内容:((HttpURLConnection) connection).setChunkedStreamingMode(1024);但我的问题是我不知道如何阅读这个被压缩的流。所以如果有人能指导我正确的方法,我会很高兴。

Thanks!

谢谢!

Sample Code :

示例代码:

TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
            String deviceId = tm.getDeviceId();
            Log.w("device_identificator","device_identificator : "+deviceId);
            String resolution = Integer.toString(getWindow().getWindowManager().getDefaultDisplay().getWidth())+ "x" +
                                         Integer.toString(getWindow().getWindowManager().getDefaultDisplay().getHeight());
            Log.w("device_resolution","device_resolution : "+resolution);
            String version = "Android " + Build.VERSION.RELEASE;
            Log.w("device_os_type","device_os_type : "+version);
            Log.w("device_identification_string","device_identification_string : "+version);
            String locale = getResources().getConfiguration().locale.toString();
            Log.w("set_locale","set_locale : "+locale);
            String clientApiVersion = null;

            PackageManager pm = this.getPackageManager();
            PackageInfo packageInfo;

            packageInfo = pm.getPackageInfo(this.getPackageName(), 0);

            clientApiVersion = packageInfo.versionName;
            Log.w("client_api_ver","client_api_ver : "+clientApiVersion);

            long timestamp = System.currentTimeMillis()/1000;
            String timeStamp = Long.toString(timestamp);


            String url = "http://www.rpc.shutdown.com";
            String charset = "UTF-8";
            String usernameHash = hashUser(username,password);
            String passwordHash = hashPass(username,password);


            String query = String.format("username_hash=%s&password_hash=%s&new_auth_data=%s&debug_data=%s&client_api_ver=%s&set_locale=%s&timestamp=%s&"+
                     "device_os_type=%s&mobile_imei=%s&device_sync_type=%s&device_identification_string=%s&device_identificator=%s&device_resolution=%s", 
                     URLEncoder.encode(usernameHash, charset), 
                     URLEncoder.encode(passwordHash, charset),
                     URLEncoder.encode("1", charset),
                     URLEncoder.encode("1", charset),
                     URLEncoder.encode(clientApiVersion, charset),
                     URLEncoder.encode(locale, charset),
                     URLEncoder.encode(timeStamp, charset),
                     URLEncoder.encode(version, charset),
                     URLEncoder.encode(deviceId, charset),
                     URLEncoder.encode("14", charset),
                     URLEncoder.encode(version, charset),
                     URLEncoder.encode(deviceId, charset),
                     URLEncoder.encode(resolution, charset));

            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setDoOutput(true); // Triggers POST.
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Charset", charset);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
            OutputStream output = null;
            try {
                 output = connection.getOutputStream();
                 output.write(query.getBytes(charset));
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                 if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
            }

            int status = ((HttpURLConnection) connection).getResponseCode();
            Log.i("","Status : "+status);

            for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
                Log.i("Headers","Headers : "+header.getKey() + "=" + header.getValue());
            }

            InputStream response = connection.getInputStream();
            Log.i("","Response : "+response.toString());
            int bytesRead = -1;
            byte[] buffer = new byte[8*1024];
            while ((bytesRead = response.read(buffer)) >= 0) {
              String line = new String(buffer, "UTF-8");
              Log.i("","line : "+line);
              handleDataFromSync(buffer);
            }

采纳答案by Vincent Mimoun-Prat

Simply allocate a byte buffer that can hold a small amount of data and read from the input stream into this buffer (using the readmethod). Something like:

只需分配一个字节缓冲区,该缓冲区可以容纳少量数据并从输入流中读取到该缓冲区中(使用read方法)。就像是:

InputStream is = connection.getInputStream();

int bytesRead = -1;
byte[] buffer = new byte[1024];
while ((bytesRead = is.read(buffer)) >= 0) {
  // process the buffer, "bytesRead" have been read, no more, no less
}

回答by Basbous

To read the Response Header try to use :

要阅读响应头尝试使用:

String sHeaderValue = connection.getHeaderField("Your_Header_Key");