getInputStream() 在设备上非常缓慢,但在模拟器上则不然

huangapple 未分类评论45阅读模式
英文:

getInputStream() very slow on device, but not on emulator

问题

(我相信这个问题已经被问过多次,但通常没有被接受的答案,或者只有非常旧或无效的解决方案。)

我的应用程序应连接到服务器并显示读取的数据。这在模拟器上运行良好,但一旦我在任何真实设备上尝试,getInputStream() 耗时非常长(15 到 20 秒,而不是 1 到 2 秒)。有趣的是,我注意到当我将 setConnectTimeout() 设置为更短的时间时,响应会稍微更快,但这可能会导致更多错误。我漏掉了什么?

我尝试过的:

connection.setUseCaches(false);
使用 HttpUrlConnection 而不是 HttpsUrlConnection
System.setProperty("http.keepAlive", "false");
connection.setRequestProperty("Content-Length", "1000");

在清单中添加 android:usesCleartextTraffic="true"
我确实看到了 "No Network Security Config specified, using platform default",但修复这个问题似乎没有帮助。

内部类 HttpGetRequest 在一个示例中找到并修改以适应我的需求:

public class HttpGetRequest extends AsyncTask<Void, Void, String> {

    static final String REQUEST_METHOD = "GET";
    static final int READ_TIMEOUT = 15000;
    static final int CONNECTION_TIMEOUT = 15000; //较短的时间工作速度更快!

    @Override
    protected void onPreExecute() {

        clipEditText.setText("loading...");
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(Void... params){

        String result="";
        String inputLine;

        //创建连接
        URL myUrl = null;
        try {
            myUrl = new URL(urlString);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        HttpsURLConnection connection = null;
        try {
            connection = (HttpsURLConnection) myUrl.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            connection.setRequestMethod(REQUEST_METHOD);
        } catch (ProtocolException e) {
            e.printStackTrace();
        }
        connection.setReadTimeout(READ_TIMEOUT);
        connection.setConnectTimeout(CONNECTION_TIMEOUT);

        //从输入流中获取字符串
        InputStreamReader streamReader = null;
        try {
            streamReader = new InputStreamReader(connection.getInputStream());
            BufferedReader reader = new BufferedReader(streamReader);
            StringBuilder stringBuilder = new StringBuilder();
            Log.d(TAG, "doInBackground: Reading...");
            while((inputLine = reader.readLine()) != null){
                stringBuilder.append(inputLine);
            }

            //完成后清理
            reader.close();
            streamReader.close();
            connection.disconnect();
            result = stringBuilder.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    protected void onPostExecute(String result){
        super.onPostExecute(result);
        clipContent = result;

        //显示数据
        clipEditText.setText(clipContent);
    }
}
英文:

(I believe this question has been asked several times, but often without an accepted answer or with very old or ineffective solutions.)

My app should connect to a server and display read data. This works fine on the emulator, but as soon as I try it on any real device, getInputStream() takes extremely long (15 to 20 seconds instead of 1 to 2 seconds). Interestingly, I have noticed slightly quicker responses when I set setConnectTimeout() to a shorter time, but this could lead to more errors. What am I missing?

What I tried:

connection.setUseCaches(false);  
using HttpUrlConnectio instead of HttpsUrlConnection  
System.setProperty(&quot;http.keepAlive&quot;, &quot;false&quot;);  
connection.setRequestProperty(&quot;Content-Length&quot;, &quot;1000&quot;);  

Adding android:usesCleartextTraffic=&quot;true&quot; to Manifest
I did see "No Network Security Config specified, using platform default", but fixing that did not seem to help.

The inner class HttpGetRequest was found in an example and adopted to suit my needs:

public class HttpGetRequest extends AsyncTask&lt;Void, Void, String&gt; {

    static final String REQUEST_METHOD = &quot;GET&quot;;
    static final int READ_TIMEOUT = 15000;
    static final int CONNECTION_TIMEOUT = 15000; //shorter time works faster!

    @Override
    protected void onPreExecute() {

        clipEditText.setText(&quot;loading...&quot;);
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(Void... params){

        String result=&quot;&quot;;
        String inputLine;

        //create connection
        URL myUrl = null;
        try {
            myUrl = new URL(urlString);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        HttpsURLConnection connection = null;
        try {
            connection = (HttpsURLConnection) myUrl.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            connection.setRequestMethod(REQUEST_METHOD);
        } catch (ProtocolException e) {
            e.printStackTrace();
        }
        connection.setReadTimeout(READ_TIMEOUT);
        connection.setConnectTimeout(CONNECTION_TIMEOUT);

         // get the string from the input stream
        InputStreamReader streamReader = null;
        try {
            streamReader = new InputStreamReader(connection.getInputStream());
            BufferedReader reader = new BufferedReader(streamReader);
            StringBuilder stringBuilder = new StringBuilder();
            Log.d(TAG, &quot;doInBackground: Reading...&quot;);
            while((inputLine = reader.readLine()) != null){
                stringBuilder.append(inputLine);
            }

            //clean up when done
            reader.close();
            streamReader.close();
            connection.disconnect();
            result = stringBuilder.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    protected void onPostExecute(String result){
        super.onPostExecute(result);
        clipContent = result;

            //show us the data
            clipEditText.setText(clipContent);
     }
}

huangapple
  • 本文由 发表于 2020年7月26日 18:18:32
  • 转载请务必保留本文链接:https://java.coder-hub.com/63098827.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定