gpt4 book ai didi

android - 收到响应后如何关闭http客户端连接?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:23:40 29 4
gpt4 key购买 nike

我正在使用 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的代码。收到响应后如何关闭此连接?

我在客户端对象上搜索了 disconnect 或 close 方法,但没有这样的方法可用。

有人可以帮忙吗?

谢谢。

最佳答案

被持有的线程和连接如果一直空闲,会自动释放。但是,如果您编写的应用程序需要主动释放未使用的资源,您可能会这样做。

使用 shutdown() 关闭调度程序的执行程序服务。这也会导致以后对客户端的调用被拒绝。

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

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

 client.connectionPool().evictAll();

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

 client.cache().close();

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

关于android - 收到响应后如何关闭http客户端连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48339019/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com