一、OkHttp
导入依赖
implementation 'com.squareup.okhttp3:okhttp:3.12.0'
get异步:
①创建OKhttpclient对象 new OkHttpClient.Builder().build();
②构建请求对象 new Request.Builder().get().url(url).build();
③获取call对象 okHttpClient.newCall(request);
④call执行请求 call.enqueue(new Callback() {}
private void getEn() {
//创建okhttpClient 对象
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new caCheInterCeptor())
.addNetworkInterceptor(new caCheInterCeptor())
.cache(new Cache(getCacheDir(), 1024 * 1024 * 60))
.build();
//构建请求对象
Request request = new Request.Builder()
.url(foodUrl + paramse + page)
.get()
.build();
//获取call对象
Call call = okHttpClient.newCall(request);
//call执行请求
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("TAG", "网络错误:" + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i("TAG", "onResponse当前线程:" + Thread.currentThread().getName());
String json = response.body().string();
Log.i("TAG", "json" + json.toString());
Gson gson = new Gson();
final FoodBean foodBean = gson.fromJson(json, FoodBean.class);
runOnUiThread(new Runnable() {
@Override
public void run() {
btn_get_en.setText(foodBean.getData().get(5).getTitle());
}
});
}
});
post异步:
①创建OKhttpclient 对象new OkHttpClient.Builder().build();
②创建请求体 new FormBody.Builder().add(“stage_id”, “1”).build();
③构建请求对象 new Request.Builder().url(url+from).post(body).build();
④获取call对象 okHttpClient.newCall(request);
⑤call执行请求 call.enqueue(new Callback() {}
private void postEn() {
//创建 okhttpClient 对象
OkHttpClient okHttpClient = new OkHttpClient.Builder()
//超时设置
.connectTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.writeTimeout(5, TimeUnit.SECONDS)
// .addInterceptor(new LogginInterCeptor())//应用拦截器
// .addNetworkInterceptor(new LogginInterCeptor())//网络拦截器
//缓存设置
.cache(new Cache(new File(getCacheDir(), "cache"), 10 * 1024 * 1024))
.build();
//创建请求体
FormBody body = new FormBody.Builder()
//表单提交
.add("stage_id", "1")
.add("limit", "20")
.add("page", "1")
.build();
//创建请求对象
Request request = new Request.Builder()
//请求头设置
.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
.header("User-Agent", "gaoxiaoqianliutao")
.url(foodUrl + paramse + page)
.post(body)
.build();
//获取call对象
Call call = okHttpClient.newCall(request);
//call执行请求
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("TAG", "网络错误:" + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//响应行
Log.i("ok", "响应行protocol=" + response.protocol() + "code=" + response.code() + "message=" + response.message());
//响应头
Headers headers = response.headers();
for (int i = 0; i < headers.size(); i++) {
Log.i("ok", headers.name(i) + ":" + headers.value(i));
}
//响应体
String json = response.body().string();
final FoodBean foodBean = new Gson().fromJson(json, FoodBean.class);
runOnUiThread(new Runnable() {
@Override
public void run() {
btn_post_en.setText(foodBean.getData().get(5).getTitle());
}
});
}
});
}
请求体
1.form:FormBody.builder().build();
private void postFrom() {
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
FormBody body = new FormBody.Builder()
.add("page", "1")
.add("limit", "20")
.add("stage_id", "1")
.build();
Request request = new Request.Builder()
.url(foodUrl + parame)
.post(body)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("TAG", "网络错误:"+e
.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String json = response.body().string();
FoodBean foodBean = new Gson().fromJson(json, FoodBean.class);
Log.i("TAG", foodBean.getData().get(2).getTitle());
}
});
}
2.string:RequestBody.create(type,"");
private void postString() {
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
MediaType mediaType = MediaType.parse(formType);
String content="stage_id=1&limit=20&page=1";
RequestBody requestBody = RequestBody.create(mediaType, content);
Request request = new Request.Builder()
.url(foodUrl + parame)
.post(requestBody)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("TAG", "网络错误:"+e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String json = response.body().string();
FoodBean foodBean = new Gson().fromJson(json, FoodBean.class);
Log.i("TAG", foodBean.getData().get(4).getTitle());
}
});
}
3.json
private void postJson() {
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
FoodJsonBean foodJsonBean = new FoodJsonBean();
foodJsonBean.setLimit("20");
foodJsonBean.setPage("1");
foodJsonBean.setStage_id("1");
Gson gson = new Gson();
String json = gson.toJson(foodJsonBean);
MediaType mediaType = MediaType.parse(jsonType);
RequestBody requestBody = RequestBody.create(mediaType, json);
Request request = new Request.Builder()
.url(foodUrl + parame)
.post(requestBody)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("TAG", "网络错误:"+e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String json = response.body().string();
FoodBean foodBean = new Gson().fromJson(json, FoodBean.class);
Log.i("TAG", foodBean.getData().get(8).getTitle());
}
});
}
4.stream:new RequestBody()
private void postSteam() {
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
RequestBody requestBody = new RequestBody() {
@Override
public MediaType contentType() {
return MediaType.parse(formType);
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
sink.writeUtf8(steamType);
}
};
Request request = new Request.Builder()
.url(foodUrl + parame)
.post(requestBody)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("TAG", "网络错误:"+e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String json = response.body().string();
FoodBean foodBean = new Gson().fromJson(json, FoodBean.class);
Log.i("TAG", foodBean.getData().get(6).getTitle());
}
});
}
5.file
请求头、缓存、超时
请求头:reques.header() request.addHeader()
缓存:okHttpClient.cacha(new Cache(file,time))
超时:ok.timeout()
二、Retrofit
retrofit依赖
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
数据解析器依赖(工厂) (直接可以response.body(),不用new Gson了,非常的方便)
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
retrofit使用步骤
①创建接口服务类:baseURL和方法
②创建retrofit对象 new Retrofit.Builder().baseUrl"(“ApiService.baseUrl”).build();
③通过retrofit对象获取接口服务对象 retrofit.create(ApiService.class);
④接口服务对象调用自己的方法 apiService.get();
⑤通过call执行请求 call.enqueue(new Callback() {}
下面是12种常用注解!!!
每个都要有一个baseUrl呦!!!
//baseUrl必须以 "/" 结尾
String baseUrl="http://www.qubaobei.com/ios/cf/";
@GET("dish_list.php?stage_id=1&limit=20&page=1")
Call<ResponseBody> get1();
private void get1() {
//获取retrofit对象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiServer.baseUrl)
.build();
//获取接口服务对象
ApiServer apiServer = retrofit.create(ApiServer.class);
//接口服务对象调用接口中的方法得到call对象
Call<ResponseBody> call = apiServer.get1();
//call执行请求
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
//当前线程
Log.i("TAG", "当前线程" + Thread.currentThread().getName());
try {
String json = response.body().string();
Log.i("TAG", "responseBody:" + json);
FoodBean foodBean = new Gson().fromJson(json, FoodBean.class);
btn_get1.setText(foodBean.getData().get(3).getTitle());
Toast.makeText(MainActivity.this, foodBean.getData().get(5).getTitle(), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}