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.