2

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

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.

How can I speed up the request?

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();
    }
Cœur
  • 37,241
  • 25
  • 195
  • 267
allegs34
  • 21
  • 1
  • 3
  • What Thread are you executing on? If you don't know much about threads just go for the async as its done in the following answer. https://stackoverflow.com/questions/34967505/android-okhttp-asynchronous-calls – loshkin Nov 14 '17 at 14:55
  • @toshkinl - i have build a class for getting json from a url, this part of the code is from that class – allegs34 Nov 14 '17 at 15:09

1 Answers1

0

You must consider some important things :

  • 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
        }
    };
    
  • Using okhttp3 thread using 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.
            }
        }
    });
    
  • 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();
    }
    
Khaled Lela
  • 7,831
  • 6
  • 45
  • 73