1、首先添加依赖
implementation ('com.squareup.okhttp3:okhttp:3.10.0')
2、测试网址
3、GET同步请求
public void get_sync(View view) {
new Thread(new Runnable() {
@Override
public void run() {
Request request = new Request.Builder().url("https://httpbin.org/get?a=1&b=2").build();
//准备请求的call对象
Call call = okHttpClient.newCall(request);
try {
Response response = call.execute();
Log.e(TAG, "get_sync: "+response.body().string() );
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
4、GET异步请求
//异步请求
public void get_nosync(View view) {
Request request = new Request.Builder().url("https://httpbin.org/get?a=1&b=2").build();
//准备请求的call对象
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e(TAG, "onFailure: ");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful())//成功
Log.d(TAG, "onResponse: " + response.body().string());
else
{
Log.e(TAG, "onFailure: ");
}
}
});
}
5、POST同步请求
public void post_sync(View view) {
new Thread(new Runnable() {
@Override
public void run() {
RequestBody requestBody = new FormBody.Builder()
.add("a", "1")
.add("b", "2")
.build();
Request request = new Request.Builder().url("https://httpbin.org/post")
.post(requestBody)
.build();
//准备请求的call对象
Call call = okHttpClient.newCall(request);
try {
Response response = call.execute();
Log.e(TAG, "get_sync: "+response.body().string() );
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
6、POST异步请求
public void post_nosync(View view) {
RequestBody requestBody = new FormBody.Builder()
.add("a", "1")
.add("b", "2")
.build();
Request request = new Request.Builder().url("https://httpbin.org/post")
.post(requestBody)
.build();
//准备请求的call对象
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e(TAG, "onFailure: ");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful())//成功
Log.d(TAG, "onResponse: " + response.body().string());
else
{
Log.e(TAG, "onFailure: ");
}
}
});
}