首先添加依賴
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'//請求結果直接轉化為實體類,省略gson轉化
創(chuàng)建一個接口
// 完整地址: http://www.wuhaojun.com/api/android/customer?type=1
public interface CustomerService {
@GET("/api/android/customer")//Get請求地址
Call<Customer> getCustomer(@Query("type") int type);//定義參數(shù)type的當前是第幾頁 1,2,3 ...
}
請求方法
String baseUrl = "http://www.wuhaojun.com/";//請求地址,固定的一部分
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())//請求結果直接轉化實體類
.build();
CustomerService movieService = retrofit.create(CustomerService.class);//創(chuàng)建對象
Call<Customer> call = movieService.getCustomer(1);//傳遞請求參數(shù) 對應接口中的定義
call.enqueue(new Callback<Customer>() {
@Override
public void onResponse(Call<Customer> call, Response<Customer> response) {
Log.i(TAG, "onResponse: "+response.body().getMessage());//返回的就是實體類,不需要Gson轉換
}
@Override
public void onFailure(Call<Customer> call, Throwable t) {
Log.i(TAG, "onFailure: "+t.getMessage());
}
});
最后,別忘了添加網(wǎng)絡權限
<uses-permission android:name="android.permission.INTERNET" />
附加其他上傳類型
//post json
@POST
Call<String> reJson(@Url String url, @Body RequestBody body);
HashMap<String, String> params = new HashMap<>();
params.put("phone_num", "123");
JSONObject json = new JSONObject(params);
RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=utf-8"), json);//轉化類型
//post params
@POST
@FormUrlEncoded
Call<String> reParams(@Url String url, @FieldMap Map<String, String> map);
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("user", "test");
//post file map
@POST
@Multipart
Call<String> reUploadFile(@Url String url, @PartMap Map<String, RequestBody> params);
File file = new File("");
Map<String, RequestBody> hashMap = new HashMap<>();
hashMap.put("json", RequestBody.create(MediaType.parse("text/plain"), "jsonargs"));//鍵值對
hashMap.put("file\"; filename=\"" + file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file));//文件
大神tough1985文章:http://gank.io/post/56e80c2c677659311bed9841