1岛杀、代碼
public class OceanUtil {
private String url;
private RequestBody requestBody;
private HttpRequestCallback httpRequestCallback;
private static OkHttpClient okHttpClient;
// 構(gòu)造方法根據(jù)需求自定義封裝
public OceanUtil(String type, JSONObject jsonObject, HttpRequestCallback httpRequestCallback) {
String domain = "http://192.168.43.108:8088/transportservice/action/";
this.url = domain + type;
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), jsonObject.toString());
this.requestBody = requestBody;
this.httpRequestCallback = httpRequestCallback;
okHttpClient = getOkHttpClient();
}
// 同步請求
public void AsynPostInfo() {
Request request = new Request.Builder().url(url).post(requestBody).build();
Call call = okHttpClient.newCall(request);
try {
Response response = call.execute();
if(response.isSuccessful())
{
String str = response.body().string();
httpRequestCallback.callback(str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void postInfo() {
Request request = new Request.Builder().url(url).post(requestBody).build();
okHttpClient.dispatcher().setMaxRequests(1);
okHttpClient.dispatcher().setMaxRequestsPerHost(1);
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String str = response.body().string();
httpRequestCallback.callback(str);
}
});
}
public void postInfo(final int time) {
Request request = new Request.Builder().url(url).post(requestBody).build();
okHttpClient.dispatcher().setMaxRequests(1);
okHttpClient.dispatcher().setMaxRequestsPerHost(1);
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String str = response.body().string();
httpRequestCallback.callback(str);
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
postInfo(time);
}
});
}
private synchronized OkHttpClient getOkHttpClient() {
if (okHttpClient == null) {
okHttpClient = new OkHttpClient();
}
return okHttpClient;
}
public interface HttpRequestCallback {
void callback(String strResponse);
}
}