- 参考:
- OkHttp使用完全教程
- OkHttp3基础篇:Home
- 官网传送门
一. 简单用法
- 同步Get:不开启新线程,要自己开启新线程进行网络请求
compile 'com.squareup.okhttp3:okhttp:3.6.0'
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("url").build();
- 调用client的newCall()方法创建一个call对象,并调用execute方法发起HTTP请求,获取服务器返回的数据(Response对象)
Response response = client.newCall(request).execute();
- 调用Reponse的body()方法获取请求到的响应体,再调用string()方法获取string形式的返回结果(如json字符串)(PS:response的这些方法只能调用一次,第二次调用会报closed异常)
String respStr = response.body().string();//返回的请求体
Log.i(TAG, response.body().contentType().toString());//返回类型
Log.i(TAG, "doInBackground: message: " + response.message());//返回信息
Log.i(TAG, "doInBackground: code: " + response.code());//请求状态码
Log.i(TAG, "doInBackground: body: " + respStr);
/**
* 开启线程进行http请求
*/
new Thread(new Runnable() {
@Override
public void run() {
String responseStr = null;
OkHttpClient client = new OkHttpClient();//实例化OkHttpClient
Request request = new Request.Builder().url(JSON).build();//构建Request
try {
Response response = client.newCall(request).execute();//发起请求
responseStr = response.body().string();//返回的结果
Log.i(TAG, "run: response "+responseStr);
} catch (IOException e) {
e.printStackTrace();
}
/*在主线程更新UI*/
final String finalResponseStr = responseStr;
runOnUiThread(new Runnable() {
@Override
public void run() {
mResponseTV.setText(finalResponseStr);
}
});
}
}).start();
- 异步Get:自动帮你开启新线程,需要在回调方法中处理逻辑
compile 'com.squareup.okhttp3:okhttp:3.6.0'
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("url").build();
- 调用client的newCall()方法创建一个call对象,并调用enqueue方法新开线程发起HTTP请求,获取服务器返回的数据(Response对象),并在回调方法里进行处理。PS:回调方法还是运行在其他线程,更新UI需要用handler操作
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
String respStr = response.body().string();
Log.i(TAG, "onResponse: respStr "+respStr);
mResponseTV.setText(respStr);
}
});
- Post请求
- 和Get请求一样,新建一个OkHttpClient
OkHttpClient client = new OkHttpClient();
- 新建MediaType对象(对应http请求里面的content-type,用来标识要post的文件类型)
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
- 新建RequestBody(请求体对象,就是要提交的对象和它的content-type)
RequestBody requestBody = RequestBody.create(JSON, String data);
- 新建Request对象(相比get请求,多连缀了一个post方法,将之前新建的RequestBody传进去即可)
Request request = new Request.Builder().url("http://" + url).post(requestBody).build();
- 调用client的newCall()方法创建一个call对象,并调用execute方法发起HTTP请求,获取服务器返回的数据(Response对象)
sOkHttpClient.newCall(request).execute();
二. 封装
public class HttpUtil {
private static OkHttpClient client = new OkHttpClient();
/**
* 异步get请求,不能返回数据
* @param address
* @param callback
*/
public static void sendOkHttpRequest(String address, Callback callback){
Request request = new Request.Builder().url(address).build();
client.newCall(request).enqueue(callback);
}
/**
* 同步get请求,可以返回数据,但是调用得开启线程
* @param address
* @return
*/
public static String sendOkHttpRequestSync(String address){
Request request = new Request.Builder().url(address).build();
try {
Response response = client.newCall(request).execute();
String respStr = response.body().string();
if(respStr!=null){
return respStr;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/*向服务器post一个json字符串*/
public static Response postJson(String url, String data) {
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody requestBody = RequestBody.create(JSON, data);
Request request = new Request.Builder().url("http://" + url).post(requestBody).build();
try {
return sOkHttpClient.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
三. 后记
- 同步请求和异步请求的区别:
- 同步请求:可以随时获得想要的数据,但是要开线程
- 异步请求:只能在回调方法中处理数据,不需要开线程(已经帮你开线程做了)