How to close http client connection after getting the response?

 ̄綄美尐妖づ 提交于 2019-12-24 09:49:32

问题


I am using http client to send a request. I want to make sure I am closing the connection after the response is received.

code:

public class WebserviceCall extends AsyncTask<Void,Void,String> {
    // interface for response
    AsyncResponse delegate;
    private final MediaType URLENCODE = MediaType.parse("application/json;charset=utf-8");
    ProgressDialog dialog;
    Context context;
    String dialogMessage;
    boolean showDialog = true;
    String URL;
    String jsonBody;
    private OkHttpClient client;

    public WebserviceCall(Context context, String URL, String jsonRequestBody, String dialogMessage, boolean showDialog, AsyncResponse delegate){
        this.context = context;
        this.URL = URL;
        this.jsonBody = jsonRequestBody;
        this.dialogMessage = dialogMessage;
        this.showDialog = showDialog;
        this.delegate = delegate;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        if(Utils.isNetworkAvailable(context)) {
            if (showDialog) {
                /*dialog = new ProgressDialog(context);
                dialog.setMessage(dialogMessage);
                dialog.show();*/
            }
        } else {
            Utils.showDialog(context, context.getString(R.string.networkWarning));
        }
    }

    @Override
    protected String doInBackground(Void... params) {
        // creating okhttp client
        client = new OkHttpClient();

        // client.setConnectTimeout(10L, TimeUnit.SECONDS);
        // creating request body
        RequestBody body;
        if(jsonBody != null) {
            body = RequestBody.create(URLENCODE, jsonBody);
        }else{
            body = null;
        };

        // creating request
        Request request = new Request.Builder()
            .post(body)
            .url(URL)
            .build();
        // creating webserivce call and get response
        try {
            Response response = client.newCall(request).execute();
            String res = response.body().string();
            Log.d("myapp", res);
            return res;
        } catch (IOException e) {
            e.printStackTrace();
            // Toast.makeText(context,"could not connect to server",Toast.LENGTH_LONG).show();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        try {
        /*if ((dialog != null) && showDialog) {
            dialog.dismiss();
        }*/
        } catch (final IllegalArgumentException e) {
            // Handle or log or ignore
        } catch (final Exception e) {
            // Handle or log or ignore
        } finally {
            dialog = null;
        }

        if (s != null) {
            delegate.onCallback(s);
        } else {
            Log.d("myapp",getClass().getSimpleName()+": response null");
        }
    }
}

Here is the code for requesting the url. How do I close this connection after the response is received?

I searched for disconnect or close method on client object but there is no such method available.

Can anyone help out please?

Thank you.


回答1:


"Calling response.body().close() will release all resources held by the response. The connection pool will keep the connection open, but that'll get closed automatically after a timeout if it goes unused." Answered here.




回答2:


The threads and connections that are held will be released automatically if they remain idle. But if you are writing a application that needs to aggressively release unused resources you may do so.

Shutdown the dispatcher's executor service with shutdown(). This will also cause future calls to the client to be rejected.

 client.dispatcher().executorService().shutdown();

Clear the connection pool with evictAll(). Note that the connection pool's daemon thread may not exit immediately.

 client.connectionPool().evictAll();

If your client has a cache, call close(). Note that it is an error to create calls against a cache that is closed, and doing so will cause the call to crash.

 client.cache().close();

You can have more detail in below link https://square.github.io/okhttp/3.x/okhttp/okhttp3/OkHttpClient.html



来源:https://stackoverflow.com/questions/48339019/how-to-close-http-client-connection-after-getting-the-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!