get 请求
//创建OkHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS) // 超时设置
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.build();
final Request request = new Request.Builder()
.url("http://XXXX.com")
.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36")
.addHeader("Host", "XXXX.com")
.get()
.build();
Call call = okHttpClient.newCall(request);
//异步操作
call.enqueue(new Callback() {
//请求错误回调方法
@Override
public void onFailure(Call call, IOException e) {
System.out.println("连接失败");
}
//异步请求(非主线程)
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.code() == 200) {
System.out.println(response.body().string());
}
}
});
post 请求 -- form表单提交
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.build();
//post方式提交的数据
FormBody formBody = new FormBody.Builder()
.add("t", "test")
.build();
final Request request = new Request.Builder()
.url("http://XXX.com")//请求的url
.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36")
.addHeader("Host", "XXXX.com")
.post(formBody)
.build();
//创建/Call
Call call = okHttpClient.newCall(request);
//加入队列 异步操作
call.enqueue(new Callback() {
//请求错误回调方法
@Override
public void onFailure(Call call, IOException e) {
System.out.println("连接失败");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.code() == 200) {
System.out.println(response.body().string());
}
}
});
post 请求 -- json格式提交
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.build();
JSONObject json = new JSONObject();
try {
json.put("t", "test");
} catch (JSONException e) {
e.printStackTrace();
}
//MediaType 设置Content-Type 标头中包含的媒体类型值
RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"), json);
Request request = new Request.Builder()
.url("http://XXX.com")//请求的url
.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36")
.addHeader("Host", "XXXX.com")
.post(requestBody)
.build();
//创建/Call
Call call = okHttpClient.newCall(request);
//加入队列 异步操作
call.enqueue(new Callback() {
//请求错误回调方法
@Override
public void onFailure(Call call, IOException e) {
System.out.println("连接失败");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
System.out.println(response.body().string());
}
});