OkHttp&单例模式思路
OkHttp
什么是OkHttp?
okhttp是一个第三方类库,用于android中请求网络。
这是一个开源项目,是安卓端最火热的轻量级框架,由移动支付Square公司贡献(该公司还贡献了Picasso和LeakCanary) 。用于替代HttpUrlConnection和Apache HttpClient(android API23 里已移除HttpClient)。
Tips
使用时需导入依赖:
implementation 'com.squareup.okhttp3:okhttp:3.12.1'
需要使用Handle来更新UI
GET请求
public void getjson(){
//TODO 1:client对象
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.callTimeout(5, TimeUnit.SECONDS);//连接超时
builder.readTimeout(5,TimeUnit.SECONDS);//读取超时
OkHttpClient client = builder.build();
//TODO 2:request对象
Request.Builder builder1 = new Request.Builder();
builder1.url("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&");//设置网址
builder1.get();//设置请求方法
Request request = builder1.build();
//TODO 3:发起连接call
Call call = client.newCall(request);
//TODO 4:通过call得到response
call.enqueue(new Callback() {
//请求失败
@Override
public void onFailure(Call call, IOException e) {
}
//请求成功
@Override
public void onResponse(Call call, Response response) throws IOException {
//获得响应体:json串
ResponseBody body = response.body();
//通过body直接转成字符串
String json = body.string();
// Toast.makeText(MainActivity.this, ""+json, Toast.LENGTH_SHORT).show();
Message obtain = Message.obtain();
obtain.what=GET_JSON_OK;
obtain.obj=json;
handler.sendMessage(obtain);
}
});
}
POST请求
private void post() {
OkHttpClient client = new OkHttpClient.Builder()
.callTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.build();
//完成请求体:
FormBody formBody = new FormBody.Builder()
.add("phone", "13594343356")
.add("passwd", "123654")
.build();
final Request request = new Request.Builder()
.url("https://www.apiopen.top/createUser?key=00d91e8e0cca2b76f515926a36db68f5&")
.post(formBody)//post提交必须要设置请求体
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String string = response.body().string();
Message obtain = Message.obtain();
obtain.what=GET_JSON_OK;
obtain.obj=string;
handler.sendMessage(obtain);
}
});