1.添加依賴
compile 'com.squareup.okhttp3:okhttp:3.4.0'
2.創(chuàng)建OkHttp實例
OkHttpClient client = new OkHttpClient();
3.創(chuàng)建Request對象
Request request = new Request.Builder().url("").build();
4.調(diào)用execute()方法來發(fā)送請求并獲取服務(wù)器返回的數(shù)據(jù)
Response response? = client.newCall(request).execute();
5.獲取返回的數(shù)據(jù)
String responseData = response.body().string();
若是發(fā)送一條post請求
1.創(chuàng)建RequestBody 對象來存放需要提交的參數(shù)
RequestBody requestBody = new FormBody.Builder().add("鍵名","值").build();
2.打開url連接并且傳遞參數(shù)
Request request = new Request.Builder().url("").post(requestBody).build();
3.調(diào)用execute()方法來發(fā)送請求并獲取服務(wù)器返回的數(shù)據(jù)
Response response? = client.newCall(request).execute();
4.獲取返回的數(shù)據(jù)
String responseData = response.body().string();
? ? ? ? ? ?
解析后臺傳來的json數(shù)據(jù)
1.添加依賴
compile 'com.google.code.gson:gson:2.7'
2.創(chuàng)建Gson對象
Gson gson = new Gson();
3.獲取返回值并進行解析
List<Product> products = gson.fromJson(jsonData,newTypeTolen<List<Product>>(){}.getType());