Retrofit 2.1入门
, map);
try {
Response<String>body=call.execute();
System.out.print(body.body());
} catch (IOException e) {
e.printStackTrace();
}
}
query 访问的参数会添加到路径(path)的后面.
实际访问的url是 http://tieba.baidu.com/sheet?name=laiqurufeng&age=22&gender=male&address=sz (模拟的访问)
encoded =true表示对url的query进行url编码,同理还有encodeValues. 这2个的值默认都是true的
如果上面的代码换成 map.put("性别","男") ,然后更改@QueryMap(encoded =false )
那么实际访问的url变成了 http://tieba.baidu.com/sheet?name=laiqurufeng&age=22&性别=%E7%94%B7&address=sz (可以看到key没有进行url编码,value进行了url编码).
Header注解
header分为key和value都固定,静态Header注解方法 和 动态Header注解方法
注意header不会相互覆盖.
静态Header
interface FixedHeader{
@Headers({ //静态Header
"Accept: application/vnd.github.v3.full+json",
"User-Agent: Retrofit-Sample-App"
})
@GET("/")
Call<ResponseBody> getResponse();
}
动态Header
interface DynamicHeader{
@Headers("Cache-Control: max-age=640000") //动态Header
@GET("/")
Call<ResponseBody> getResponse(
@Header("header1")String header1,
@Header("header2")String header2);
//动态Header,其value值可以在调用这个方法时动态传入.
}
例子:
public class PhoneResult {
/**
* errNum : 0
* retMsg : success
* retData : {"phone":"15210011578","prefix":"1521001","supplier":"移动","province":"北京","city":"北京","suit":"152卡"}
*/
public int errNum;
public String retMsg;
/**
* phone : 15210011578
* prefix : 1521001
* supplier : 移动
* province : 北京
* city : 北京
* suit : 152卡
*/
public RetDataEntity retData;
public static class RetDataEntity {
public String phone;
public String prefix;
public String supplier;
public String province;
public String city;
public String suit;
@Override
public String toString() {
return "RetDataEntity{" +
"phone='" + phone + '\'' +
", prefix='" + prefix + '\'' +
", supplier='" + supplier + '\'' +
", province='" + province + '\'' +
", city='" + city + '\'' +
", suit='" + suit + '\'' +
'}';
}
}
}
Service:
动态Header
public interface PhoneService {
@GET("/apistore/mobilenumber/mobilenumber")
Call<PhoneResult> getResult(
@Header("apikey")String apikey,
@Query("phone")String phone
);
}
静态Header
public interface PhoneServiceDynamic {
@Headers("apikey:8e13586b86e4b7f3758ba3bd6c9c9135")
@GET("/apistore/mobilenumber/mobilenumber")
Call<PhoneResult> getResult(
@Query("phone")String phone
);
}
调用
public static void phone_Query(String phone){
final String BASE_URL="http://apis.baidu.com";
final String API_KEY="8e13586b86e4b7f3758ba3bd6c9c9135";
//1.创建Retrofit对象
Retrofit retrofit=new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
//2.创建访问API的请求
PhoneService service=retrofit.create(PhoneService.class);
Call<PhoneResult>call=service.getResult(API_KEY,phone);
//3.发送请求
try {
Response<PhoneResult>response=call.execute();
//4.处理结果
if (response.isSuccessful()) {
PhoneResult result=response.body();
if (result!=null) {
PhoneResult.RetDataEntity entity = result.getRetData();
System.out.print(entity.toString());
}
}
} catch (IOException e) {
e.printStackTrace();
}
/*异步调用
call.enqueue(new Callback<PhoneResult>() {
@Override
public void onResponse(Call<PhoneResult> call, Response<PhoneResult> response) {
//4.处理结果
if (response.isSuccessful()) {
PhoneResult result=response.body();
if (result!=null) {
PhoneResult.RetDataEntity entity = result.getRetData();
System.out.print(entity.toString());
}
}
}
@Override
public void onFailure(Call<PhoneResult> call, Throwable t) {
}
});*/
}
上传文件
public interface UploadServer {
@Headers({//静态Header
"User-Agent: androidphone"
})
@Multipart
@POST("/service.php?mod=avatar&type=big")
// upload is a post field
// without filename it didn't work! I use a constant name because server doesn't save file on original name
//@Part("filename=\"1\" ") RequestBody
//以表单的形式上传图片
Call<JsonObject> uploadImageM(@Part("file\";filename=\"1") RequestBody file);
// Call<ResponseBody> uploadImage(@Part("file\"; filename=\"image.png\"") RequestBody file);
/**
* 以二进制流的形式上传 图片
* @param file
* @return
*/
@Headers({//静态Header
"User-Agent:androidphone"
})
@POST("/service.php?mod=avatar&type=big")
Call<ResponseBody> uploadImage(@Body RequestBody file);
}
调用
public static void upload(String fpath) { // path to file like /mnt/sdcard/myfile.txt
String baseurl="http://dev.123go.net.cn";
File file = new File(fpath);
// please check you mime type, i'm uploading only images
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
/*RequestBody rbody=new MultipartBody.Builder()
.addPart(requestBody).build();
RequestBody requestFile =
RequestBody.create(MediaType.parse("image/jpg"), file);
MultipartBody.Part body =
MultipartBody.Part.createFormData("image", file.getName(), requestFile);
*/
Retrofit retrofit=new Retrofit.Builder()
.baseUrl(baseurl)
.addConverterFactory(GsonConverterFactory.create())
.client(getOkhttpClient())
.build();
// 添加描述
/*String descriptionString = "hello, 这是文件描述";
RequestBody description =
RequestBody.create(
MediaType.parse("multipart/form-data"), descriptionString);*/
UploadServer server=retrofit.create(UploadServer.class);
Call<ResponseBody> call = server.uploadImage(requestBody);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
ResponseBody jsonObject=response.body();
System.out.print(jsonObject.toString());
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}
private static OkHttpClient getOkhttpClient(){
final String cookie="your cookie";
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request()
.newBuilder()
// .addHeader("Content-Type", " application/x-www-form-urlencoded; charset=UTF-8")
// .addHeader("Accept-Encoding", "gzip, deflate")
// .addHeader("Connection", "keep-alive")
// .addHeader("Accept", "***")
.addHeader("Cookie", cookie)
.build();
return chain.proceed(request);
}
})
.build();
return httpClient;
}