Retrofit是Square公司开发的一款针对Android网络请求的框架,Retrofit底层基于OkHttp实现的,与其他网络框架不同的是它更多使用运行时注解的方式提供功能
- 使用前的准备工作
添加依赖
compile'com.squareup.retrofit2:retrofit:2.1.0'
compile'com.squareup.retrofit2:converter-gson:2.1.0'
- 应用
- get请求接口
例子:
通过get获取基站位置
接口详情:
http://api.haoservice.com/api/getlbs?mcc=460&mnc=0&cell_id=17984012&lac=4190&type=2&key=80bad67eb9bd4f3aa68b52f5d747c91b
接口描述:通过haoservice第三方平台提供的接口查询基站位置信息
首先,编写网络接口
public interface JiZhanPosition{
@GET ("{path}/getlbs?")
Call<Position> getPosition(@Path("path") String path, @QueryMap Map<String,String> options);
}
Position是接口返回的实体类,通过Gson转化的。@Path,用来动态的配置URL地址。@QueryMap,用来动态指定查询条件组。单个查询条件可以使用@Query.
其次,创建Retrofit,并创建接口文件
/**
* 请求基站的位置信息
* @param mcc
* @param mnc
* @param cell_id
* @param lac
* @param type
* @param key
*/
private void getPositionThoughGet(String mcc, String mnc, String cell_id, String lac, String type, String key) {
String url = "http://api.haoservice.com";
Map<String, String> map = getQueryMap(mcc, mnc, cell_id, lac, type, key);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitInterfaces.JiZhanPosition jiZhanPosition = retrofit.create(RetrofitInterfaces.JiZhanPosition.class);
Call<Position> call = jiZhanPosition.getPosition("/api", map);
call.enqueue(new Callback<Position>() {
@Override
public void onResponse(Call<Position> call, Response<Position> response) {
Position position = response.body();
String a = position.getLocation().getAddressDescription();
Toast.makeText(getApplicationContext(), a, Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Call<Position> call, Throwable t) {
}
});
}
@NonNull
/**
* 获取请求参数
*/
private Map<String, String> getQueryMap(String mcc, String mnc, String cell_id, String lac, String type, String key) {
Map<String, String> map = new HashMap<>();
map.put("mcc", mcc);
map.put("mnc", mnc);
map.put("cell_id", cell_id);
map.put("lac", lac);
map.put("type", type);
map.put("key", key);
return map;
}
post请求接口
1.传输数据类型为键值对:@Field
//通过post请求信标设备的位置,请求参数为键值对
public interface XinBiaoLocation{
@FormUrlEncoded
@POST("/WebService/GLService.asmx/GetMemberPositioningByImeis")
Call<Position> getPositionByPost(@Field("imeis") String options);
}
首先用 @FormUrlEncoded来标注这是一个表单请求,@Field(“imeis”) 用@Field来标注String类型数据的键
2.传输数据类型Json字符串:@Body
//通过post请求信标设备的位置,请求参数为json字符串
public interface XinBiaoLocation2{
@POST("/WebService/GLService.asmx/GetMemberPositioningByImeis")
Call<String> getPositionByPost(@Body Position position);
}
@Body 这个注解标识参数对象,Retrofit会将Position这个实体类转为json字符串。
- 单个文件上传
/**
* 传一张图片,测试可以 图片上传的全路径eg: http://gq.xun365.net/reuplf_exp.aspx?imei=20YJY2HA&createDate=20180129163455&lat=0.0&lng=0.0&type=0
*/
public interface GaoQingTuChuanPost{
@Multipart
@POST("/reuplf_exp.aspx?")
Call<ResponseBody> uploadImageFile(@QueryMap Map<String,String> map,
@Part("file\"; filename=\"image.jpg\"") RequestBody file);
}
@Multipart标识表示允许多个@part.@QueryMap标识请求参数。@part表示单个文件上传。
/**
* 传一个图片
*/
public void uploadImagePost() {
Log.e("888888", getCurrentTime());
String url = "http://gq.xun365.net";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
Map<String, String> map = new HashMap<>();
map.put("imei", "20YJY2HA");
map.put("createDate", "20180129163455");
map.put("lat", "88.0");
map.put("lng", "118.0");
map.put("type", "0");
RetrofitInterfaces.GaoQingTuChuanPost responseBody = retrofit.create(RetrofitInterfaces.GaoQingTuChuanPost.class);
Call<ResponseBody> responseBodyCall = responseBody.uploadImageFile(map, getRequestBody());
responseBodyCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.e("888888", getCurrentTime());
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("888888", getCurrentTime());
}
});
}
private RequestBody getRequestBody() {
File[] files = new File(srcFilePath).listFiles();
RequestBody requestBody =
RequestBody.create(MediaType.parse("multipart/form-data"), files[1]);
return requestBody;
}