【问题标题】:How to close http client connection after getting the response?收到响应后如何关闭http客户端连接?
【发布时间】:2018-01-19 10:31:55
【问题描述】:

我正在使用 http 客户端发送请求。我想确保在收到响应后关闭连接。

代码:

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

这里是请求 url 的代码。收到响应后如何关闭此连接?

我在客户端对象上搜索了断开或关闭方法,但没有可用的方法。

有人可以帮忙吗?

谢谢。

【问题讨论】:

  • 为什么不使用 Retrofit 或 Volley、Fast-Android-Networking、async-http-client 库

标签: android http httpclient okhttp


【解决方案1】:

被持有的线程和连接如果保持空闲状态将被自动释放。但是,如果您正在编写一个需要积极释放未使用资源的应用程序,您可以这样做。

使用shutdown() 关闭调度器的执行器服务。这也将导致未来对客户端的调用被拒绝。

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

使用 evictAll() 清除连接池。请注意,连接池的守护线程可能不会立即退出。

 client.connectionPool().evictAll();

如果您的客户端有缓存,请调用 close()。请注意,针对已关闭的缓存创建调用是错误的,这样做会导致调用崩溃。

 client.cache().close();

您可以在下面的链接中获得更多详细信息 https://square.github.io/okhttp/3.x/okhttp/okhttp3/OkHttpClient.html

【讨论】:

  • 嗨,我不想导致以后对客户的呼叫被拒绝。我只想在响应后关闭连接并清除资源或缓存。
【解决方案2】:

“调用 response.body().close() 将释放响应所占用的所有资源。连接池将保持连接打开,但如果未使用,则会在超时后自动关闭。” Answered here.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-04
    • 1970-01-01
    • 2011-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-12
    相关资源
    最近更新 更多