okhttp 3非常慢 [英] okhttp 3 very slow

查看:914
本文介绍了okhttp 3非常慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I try to get json from a server, I use https on the server and every http request will go to the https version.

我得到了数据,并且我发送的数据也可以发送给,但是最多需要45秒才能获得响应.相同的代码使用android的http处理程序更快.

I get the data and the data that I send works to but it takes up to 45 sec to get a response back. The same code was faster with the build in http handler of android.

如何加快请求速度?

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();
    }

推荐答案

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

You must consider some important things :

  • AsyncTask一样从UI thread执行Okhttp3请求.
  • 不要在完成后忘记关闭响应正文.

  • Executing Okhttp3 request away from UI thread, like AsyncTask.
  • Don't forget to close response body after complete.

    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
    }
};

  • 使用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并配置超时.

  • Creating OkHttp3Client and configure timeout.

    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();
    }
    

  • 这篇关于okhttp 3非常慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆