首先配置build.gradle
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'//ConverterFactory的Json依赖包,让JSON和Java对象相互转换,这里需要值得注意的是导入的retrofit2包的版本必须要一致,否则就会报错。
compile 'com.squareup.retrofit2:converter-scalars:2.3.0'//ConverterFactory的String依赖包
Retrofit进行网络请求,首先创建一个接口,然后创建Retrofit对象,并创建接口和Call对象,最后用Call的enqueue()进行异步请求,这里只需要在回调的Callback里进行处理请求结果就可以了,回调的Callback是运行在UI线程中如果想要取消请求使用Call的cancel()。
GET方法:
url:http://www.baidu.com
public interface TestString {
@GET("/")
Call getMsg();
}
String url = "http://www.baidu.com/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
TestString testString = retrofit.create(TestString.class);
Call call = testString.getMsg();
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
String string = response.body();
Log.d("TAG",string);
}
@Override
public void onFailure(Call call, Throwable t) {
t.printStackTrace();
}
});
url = baseUrl+ @GET(“/”)中的URL拼接而成,若url和baseUrl相同则@GET(“/”)中的URL使用/即可
服务器返回的数据为JSON { "error_code": 0,"reason": "Success","result": [{"cityId": "2", "cityName": "安徽","provinceId": "2"},{"cityId": "45", "cityName": "黄山","provinceId": "2"},{"cityId": "42","cityName": "合肥","provinceId": "2"},{"cityId": "51","cityName": "宣城","provinceId": "2"}]}
public class Root {
private int error_code;
private String reason;
private List result ;
public void setError_code(int error_code){
this.error_code = error_code;
}
public int getError_code(){
return this.error_code;
}
public void setReason(String reason){
this.reason = reason;
}
public String getReason(){
return this.reason;
}
public void setResult(List result){
this.result = result;
}
public List getResult(){
return this.result;
}
}
public class Result {
private String cityId;
private String cityName;
private String provinceId;
public void setCityId(String cityId){
this.cityId = cityId;
}
public String getCityId(){
return this.cityId;
}
public void setCityName(String cityName){
this.cityName = cityName;
}
public String getCityName(){
return this.cityName;
}
public void setProvinceId(String provinceId){
this.provinceId = provinceId;
}
public String getProvinceId(){
return this.provinceId;
}
}
url:http://10.0.2.2:8080/myweb/test3.json
public interface TestJson {
@GET("myweb/test3.json")
Call getMsg();
}
String url = "http://10.0.2.2:8080/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
TestJson testJson = retrofit.create(TestJson.class);
Call call = testJson.getMsg();
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
List result = response.body().getResult();
for(Result r:result){
String cityName = r.getCityName();
String provinceId = r.getProvinceId();
Log.d("TAG",provinceId);
Log.d("TAG",cityName);
}
}
@Override
public void onFailure(Call call, Throwable t) {
t.printStackTrace();
}
});
url = baseUrl+@GET(“myweb/test3.json”)中的url,即为:http://10.0.2.2:8080/myweb/test3.json
@Query
url : http://ip.taobao.com/service/getIpInfo.php?ip=116.231.198.217
public interface IpService {
@GET("service/getIpInfo.php")
Call getMsg(@Query("ip")String ip);
}
这里查询ip为116.231.198.217的信息,url = baseUrl+@GET(“service/getIpInfo.php”)中的url+ip=调用getMsg中传染的116.231.198.217。
@QueryMap
http://www.tuling123.com/openapi/api?key=354358ca75d24db7a353f67ce1589270&info=上海天气怎么样&loc=上海
public interface Weather {
@GET("openapi/api")
Call getMsg(@QueryMap Map info);
}
这里查询条件为key=354358ca75d24db7a353f67ce1589270、info=上海天气怎么样、loc=上海,url=baseUrl+@GET(“openapi/api”)中的url+info,这里的info即为传入的map数据
动态配置URL:@Path
url: http://10.0.2.2:8080/myweb/test2.json
public interface TestJson2 {
@GET("myweb/{path}.json")
Call getMsg(@Path("path")String path);
}
在GET注解中{path}对应着@path中的“path”,而用来替换{path}中的正是需要传入的String path的值。url = baseUrl+@GET(“myweb/{path}.json”)中的URL,
其中{path}为传入的String path的值
POST方法:
请求体的数据类型为键值对时:@Field
url:http://10.0.2.2:8080/test4/test
public interface TestPost {
@FormUrlEncoded
@POST("test4/test")
Call getMsg(@Field("userName")String userNmae,@Field("passWord")String passWord);
}
String url = "http://10.0.2.2:8080/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
TestPost post = retrofit.create(TestPost.class);
Call call = post.getMsg("aaaaa","bbbbb");
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
String post = response.body();
Log.d("TAG",post);
}
@Override
public void onFailure(Call call, Throwable t) {
t.printStackTrace();
}
});
使用@FormUrlEncoded说明这是一个表单请求,@Field(“userName”)表示键是userName,@Field(“passWord”)表示键是passWord;故上传的2个键值对为:userName=aaaaa&passWord=bbbbb
请求体的数据类型为多个键值对时:@FieldMap
public interface TestFieldMap {
@FormUrlEncoded
@POST("openapi/api")
Call getPostMap(@FieldMap Map fields);
}
String url = "http://www.tuling123.com/";
Map map = new HashMap<>();
map.put("key","354358ca75d24db7a353f67ce1589270");
map.put("info","上海天气怎么样");
map.put("loc","上海");
Retrofit retrofits = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
TestFieldMap testFieldMap = retrofits.create(TestFieldMap.class);
Call call = testFieldMap.getPostMap(map);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
String text = response.body().getText();
Log.d("TAG",text);
}
@Override
public void onFailure(Call call, Throwable t) {
t.printStackTrace();
}
});
请求体数据为JSON时 @Body,将实例对象根据转换方式转换为对应的json字符串参数,
public interface TestBody {
@POST("test4/test")
Call postBody(@Body BodyInfo bodyInfo);
}
public class BodyInfo {
private String userName;
private String passWord;
public BodyInfo(String userName,String passWord){
this.userName = userName;
this.passWord = passWord;
}
}
单个文件上传 @Part
public interface Part {
@Multipart
@POST("test4/test")
Call postPart(@retrofit2.http.Part MultipartBody.Part file, @retrofit2.http.Part("description")RequestBody description);
}
@Multipart表示允许上传多个@Part,第一个参数表示上传的文件,第二个参数通常是对该文件的描述
多个文件上传 @PartMap
public interface PartMap {
@Multipart
@POST("test4/test")
Call parMap(@retrofit2.http.PartMap Mapfiles, @retrofit2.http.Part("description") RequestBody description);
}
File file = new File(getFilesDir(),"okhttp.txt");
try {
FileOutputStream out = new FileOutputStream(file);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write("Hello retrofit");
writer.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
RequestBody fileRequestBody = RequestBody.create(MediaType.parse("application/octet-stream"),file);
String currentApkPath = getApplicationContext().getPackageResourcePath();
File apkFile = new File(currentApkPath);
RequestBody fileRequestBody = RequestBody.create(MediaType.parse("application/octet-stream"),apkFile);
Map maps = new HashMap<>();
maps.put("first",fileRequestBody);
maps.put("second",fileRequestBody);
String url = "http://10.0.2.2:8080/";
Retrofit retrofitPart = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
PartMap partMap = retrofitPart.create(PartMap.class);
Call call = partMap.parMap(maps,RequestBody.create(null,"success"));
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
Log.d("TAG",response.body());
textView.setText(response.body());
}
@Override
public void onFailure(Call call, Throwable t) {
t.printStackTrace();
}
});