1、okhttp3簡介:
一個處理網(wǎng)絡(luò)請求的開源項目,是安卓端最火熱的輕量級框架
2、okhttp3配置
1.Android Studio 配置gradle:
implementation 'com.squareup.okhttp3:okhttp:3.12.0'
2,添加網(wǎng)絡(luò)權(quán)限:
<uses-permission android:name="android.permission.INTERNET"/>
03坟岔、okhttp3使用思路
get請求思路
1.獲取okHttpClient對象
2.構(gòu)建Request對象
3.構(gòu)建Call對象
4.通過Call.enqueue(callback)方法來提交異步請求拼苍;execute()方法實現(xiàn)同步請求
post請求思路
1.獲取okHttpClient對象
2.創(chuàng)建RequestBody
3.構(gòu)建Request對象
4.構(gòu)建Call對象
5.通過Call.enqueue(callback)方法來提交異步請求徘郭;execute()方法實現(xiàn)同步請求
04来庭、OkHttp3 發(fā)送異步請求(GET)
String url = "http://";
//第一步獲取okHttpClient對象
OkHttpClient client = new OkHttpClient();
//第二步構(gòu)建Request對象
Request request = new Request.Builder()
.url(url)
.get()
.build();
//第三步構(gòu)建Call對象
Call call = client.newCall(request);
//第四步:異步get請求
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("onFailure", e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string();
Log.i("result", result);
}
});
05妒蔚、OkHttp3 發(fā)送異步請求(POST)
//接口參數(shù) String username,String password
String url = "http://";
//第一步創(chuàng)建OKHttpClient
OkHttpClient client = new OkHttpClient.Builder()
.build();
//第二步創(chuàng)建RequestBody(Form表達)
RequestBody body = new FormBody.Builder()
.add("username", "admin")
.add("password", "123456")
.build();
//第三步創(chuàng)建Rquest
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
//第四步創(chuàng)建call回調(diào)對象
final Call call = client.newCall(request);
//第五步發(fā)起請求
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("onFailure", e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string();
Log.i("result", result);
}
});