【问题标题】:okhttp 3 very slowokhttp 3 很慢
【发布时间】:2018-07-24 19:57:02
【问题描述】:

我尝试从服务器获取 json,我在服务器上使用 https,每个 http 请求都会转到 https 版本。

我得到了数据并且我发送到的数据可以工作,但是最多需要 45 秒才能得到回复。使用 android 的内置 http 处理程序,相同的代码更快。

如何加快请求速度?

try {
        OkHttpClient client = new OkHttpClient();
        FormBody.Builder formBuilder = new FormBody.Builder().add("key", "2285");
        //formBuilder.add("phone", "000000");

        RequestBody formBody = formBuilder.build();
        Log.v("JsonRespons", reqUrl);
        Request request = new Request.Builder()
                .url(reqUrl)
                .post(formBody)
                .build();

        okhttp3.Response response = null;

        response = client.newCall(request).execute();

        if (!response.isSuccessful()) {
            throw new IOException(response.message() + " " + response.toString());
        } else {
            output = response.body().string();
        }

        if(output != null) {
            Log.v("JsonRespons", output.toString());
        }
    } catch (IOException e) {
         e.printStackTrace();
    }

【问题讨论】:

  • 你在哪个线程上执行?如果您对线程知之甚少,只需按照以下答案中的方式选择异步即可。 stackoverflow.com/questions/34967505/…
  • @toshkinl - 我已经构建了一个从 url 获取 json 的类,这部分代码来自该类

标签: android okhttp3


【解决方案1】:

你必须考虑一些重要的事情:

  • UI thread 执行Okhttp3 请求,例如AsyncTask
  • 别忘了完成后关闭响应正文。

        new AsyncTask<String,Void,String>(){
    
        @Override
        protected String doInBackground(String... strings) {
            String strResponse = null;
            try {
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    strResponse = response.body().string();
                    response.close();  // DON't forget to close body =@response.body().close();
                }
    
            }catch (Exception ex){
            }
            return strResponse;
        }
    
        @Override
        protected void onPostExecute(String s) {
            // Update UI here
        }
    };
    
  • 使用okhttp3 线程使用enqueue

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            // When failure 
            mActivity.runOnUiThread(); // If need to update UI
        }
    
        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (response.isSuccessful()){
                String result = response.body().string();
                mActivity.runOnUiThread(); // update UI under UI thread.
                response.close();  // close response body.
            }
        }
    });
    
  • 创建OkHttp3Client 并配置超时。

    private static OkHttpClient createHttpclient() {
    final OkHttpClient.Builder builder =  new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS);
    setSocketFactory(builder); // To handle SSL certificate. 
    return builder.build();
    }
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-28
    • 2011-11-21
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多