首先引入okhttp網絡框架,很簡單如圖:在app項目中的build.gradle裏的dependencies
裏添加compile ‘com.squareup.okhttp3:okhttp:3.2.0’ 這句代碼依賴。
然後點擊Sync Now即可使用。
Get請求(主要獲取數據)
//構造request對象
Request request = new Request.Builder().get().url("https://www.baidu.com")
.build();
//創建okhttpClient對象
OkHttpClient okHttpClient = new OkHttpClient();
//獲取call對象
Call call = okHttpClient.newCall(request);
//異步請求
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
//請求失敗異常處理
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//請求成功獲取數據
String string = response.body().string();
}
});
Post請求(主要提交數據給服務端,需要請求體,responseBody根據類似鍵值對的添加來傳遞)
//創建okhttpClient對象
OkHttpClient okHttpClient = new OkHttpClient();
FormBody.Builder requestBuild = new FormBody.Builder();
//這裏根據鍵值對來添加要傳遞的數據給服務端
RequestBody requestBody = requestBuild.add
("username", "niubi").add("password", "324").build();
//構造request
Request request = new Request.Builder()
.post(requestBody)
.url(baseUrl + "login")//服務器地址
.build();
//獲取call對象
Call call = okHttpClient.newCall(request);
//異步請求
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
//請求失敗異常處理
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});