Попробуйте создать AsynTask как открытый класс NetworkClientOkhttp extends AsyncTask {
private OkHttpClient client;
private OkHttpClient.Builder builder = null;
private String mUrl;
private String mParams;
private ResponseListener responseListener;
public NetworkClientOkhttp(String mUrl, String mParams, ResponseListener responseListener) {
this.mUrl = mUrl;
this.mParams = mParams;
this.responseListener = responseListener;
builder = new OkHttpClient.Builder();
builder.connectTimeout(60, TimeUnit.SECONDS);
builder.writeTimeout(60, TimeUnit.SECONDS);
builder.readTimeout(60, TimeUnit.SECONDS);
client = builder.build();
this.execute();
}
public void sendRequest() {
RequestBody formBody = new FormBody.Builder()
.add("params", mParams)
.build();
Request request = new Request.Builder()
.url(mUrl)
.post(formBody)
.build();
try {
Response response = client.newCall(request).execute();
String res = response.body().string();
if (responseListener != null) {
responseListener.onReceiveResponse(res);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendFormBodyRequest() {
try {
JSONObject object = new JSONObject(mParams);
FormBody.Builder formBody = new FormBody.Builder();
while (object.keys().hasNext()) {
String keyName = object.keys().next();
formBody.add(keyName, object.optString(keyName));
}
RequestBody requestBody = formBody.build();
Request request = new Request.Builder()
.url(mUrl)
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
String res = response.body().string();
if (responseListener != null) {
responseListener.onReceiveResponse(res);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
protected String doInBackground(Void... voids) {
RequestBody formBody = new FormBody.Builder()
.add("params", mParams)
.build();
Request request = new Request.Builder()
.url(mUrl)
.header("issecuritydisable", "0")
.post(formBody)
.build();
try {
Response response = client.newCall(request).execute();
String res = response.body().string();
return res;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String res) {
super.onPostExecute(res);
if(!TextUtils.isEmpty(res)){
if (responseListener != null) {
responseListener.onReceiveResponse(res);
}
}
}
}