以前一直使用Retrofit2來進(jìn)行網(wǎng)絡(luò)請求,偶然的一次機(jī)會(huì),項(xiàng)目要求使用同步的網(wǎng)絡(luò)請求方式,我們都知道,Retrofit2使用異步的方式請求網(wǎng)絡(luò)(為了避免同步請求網(wǎng)絡(luò)阻塞UI線程).下面是詳細(xì)步驟 :
第一步 :
添加依賴包 :
// okhttp3的依賴
compile 'com.squareup.okhttp3:okhttp:3.8.1'
// gson解析的依賴
compile 'com.google.code.gson:gson:2.8.0'
如果你已經(jīng)添加了Retrofit2的依賴包,也可以 :
// Retrofit2的依賴
compile 'com.squareup.retrofit2:retrofit:2.3.0'
// gson解析的依賴
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
第二步 :
AndroidManifest.xml中添加網(wǎng)絡(luò)權(quán)限 :
<uses-permission android:name="android.permission.INTERNET"/>
第三步 :
封裝4個(gè)函數(shù) : get 的同/異步方式, post 的同/異步方式
注意 : 同步get/post請求,都要放在子線程中,否則會(huì)報(bào)異常 : NetworkOnMainThreadException
3.1 get 同步請求
public static String getSync(String url){
String s="";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build(); //創(chuàng)建url的請求
Response response = null;
try {
response = client.newCall(request).execute(); //execute() : 同步, enqueue() : 異步
s = response.body().string(); //獲取數(shù)據(jù)
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
獲取到數(shù)據(jù)后(以Json數(shù)據(jù)為例),創(chuàng)建Bean類,并使用Gson來解析Json字符串 :
String s = OkHttp3Util.getSync(請求的url);
if (!TextUtils.isEmpty(s)) {
Gson gson = new Gson();
DataBean bean = gson.fromJson(s, DataBean.class);
if (bean != null) {
//操作數(shù)據(jù)....
}
}
3.2 post 同步請求
public static String postSync(String url, String body) { //body為參數(shù)列表
String s = "";
OkHttpClient client = new OkHttpClient();
//"application/x-www-form-urlencoded" form表單數(shù)據(jù)被編碼為key/value格式發(fā)送到服務(wù)器(表單默認(rèn)的提交數(shù)據(jù)的格式)
RequestBody requestBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), body);
Request request = new Request.Builder().url(url).post(requestBody).build();
try {
Response response = client.newCall(request).execute();
s = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
3.3 get 異步請求
public static void getAsync(String url, Callback callback) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(callback);
}
調(diào)用方式 :
OkHttp3Util.getAsync(請求的url, 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();
if (!TextUtils.isEmpty(string)) {
Gson gson = new Gson();
AccountInfoBean bean = gson.fromJson(string, AccountInfoBean.class);
//數(shù)據(jù)操作
}
}
});
3.4 post 異步請求
public static void postAsync(String url,String body,Callback callback) {
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), body);
Request request = new Request.Builder().url(url).post(requestBody).build();
client.newCall(request).enqueue(callback);
}
調(diào)用方式與get 異步請求類似