OkHttp使用Get和Post两种请求方式
- 导入依赖包
com.squareup.okhttp3:okhttp:3.2.0
发起 Get 请求
private void getInChildThread(String url) {
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
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 {
if (response.isSuccessful()){
String result = response.body().string();
LogUtils.e(TAG,"OkHttpTestActivity.getInChildThread,result="+result);
}
}
});
}
发起 Post 请求
private void postInChildThread(String url) {
OkHttpClient okHttpClient = new OkHttpClient();
FormBody.Builder bodyBuilder = new FormBody.Builder();
bodyBuilder.add("offset","0");
bodyBuilder.add("size","10");
RequestBody body = bodyBuilder.build();
Request request = new Request.Builder().url(url).post(body).build();
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 {
if (response.isSuccessful()){
String result = response.body().string();
LogUtils.e(TAG,"OkHttpTestActivity.postInChildThread,result="+result);
}
}
});
}