添加如下依赖:
compile 'com.squareup.retrofit2:retrofit:2.3.0'
1:转换网页的json数据成为bean文件,其中用到了@GET,@Query标识符,注意了:baseUrl和注解中url连接的”/”最好写在baseUrl的后面,而不是注解中url的前面,否则可能会出现不可预知的错误。
注意如果要转换json数据的话,再添加如下依赖:
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
//注意当添加了这个依赖后,相当于添加了gson这个库
public class MainActivity extends AppCompatActivity{
private Retrofit retrofit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
retrofit=new Retrofit.Builder().baseUrl("http://www.imooc.com/api/").addConverterFactory(GsonConverterFactory.create()).build();
fuwujiekou f=retrofit.create(fuwujiekou.class);
Callcall= f.getxinxi(3);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
Example example=response.body();
Log.i("xinxi",example.getMsg());
Log.i("xinxi",example.getData().get(2).getDescription());
Log.i("xinxi",example.getStatus().toString());
}
@Override
public void onFailure(Call call, Throwable t) {
}
});
}
}
public interface fuwujiekou {
@GET(value = "teacher?type=4")
Call getxinxi(@Query("num")int i);//这里的参数是动态填写的,也可以静态写在value中
/*@GET(value = "teacher?")// 这种写法:@GET(value = "teacher")也对
Call getxinxi(@Query("type")int ii, @Query("num")int i);//请求的是两个参数,对应的MainActivity.java中要写成Call call= f.getxinxi(4,3);*/
}
public class Example {
private Integer status;
private List data = null;
private String msg;
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public List getData() {
return data;
}
public void setData(List data) {
this.data = data;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
public class Datum {
private Integer id;
private String name;
private String picSmall;
private String picBig;
private String description;
private Integer learner;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPicSmall() {
return picSmall;
}
public void setPicSmall(String picSmall) {
this.picSmall = picSmall;
}
public String getPicBig() {
return picBig;
}
public void setPicBig(String picBig) {
this.picBig = picBig;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getLearner() {
return learner;
}
public void setLearner(Integer learner) {
this.learner = learner;
}
}
2:输出网页的内容
需要另外添加如下依赖:
compile 'com.squareup.retrofit2:converter-scalars:2.3.0'
public class MainActivity extends AppCompatActivity {
private Retrofit retrofit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
retrofit = new Retrofit.Builder().baseUrl("http://www.imooc.com/").addConverterFactory(ScalarsConverterFactory.create()).build();//ScalarsConverterFactory是访问字符串要用到的,需要添加compile 'com.squareup.retrofit2:converter-scalars:2.3.0'依赖
StringInterface stringInterface = retrofit.create(StringInterface.class);
Call call = stringInterface.getString();
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
Log.d("MainActivity", response.body());
/* 输出内容为:
03 - 08 21:21:34.274 7500 - 7500 / com.example.liang.lianxi D / MainActivity:{
"status":1, "data":[{
"id":1, "name":
"Tony\u8001\u5e08\u804ashell\u2014\u2014\u73af\u5883\u53d8\u91cf\u914d\u7f6e\u6587\u4ef6", "picSmall":
"http:\/\/img.mukewang.com\/55237dcc0001128c06000338-300-170.jpg", "picBig":
"http:\/\/img.mukewang.com\/55237dcc0001128c06000338.jpg", "description":
"\u4e3a\u4f60\u5e26\u6765shell\u4e2d\u7684\u73af\u5883\u53d8\u91cf\u914d\u7f6e\u6587\u4ef6", "learner":
12312
},{
"id":2, "name":
"\u6570\u5b66\u77e5\u8bc6\u5728CSS\u52a8\u753b\u4e2d\u7684\u5e94\u7528", "picSmall":
"http:\/\/img.mukewang.com\/55249cf30001ae8a06000338-300-170.jpg", "picBig":
"http:\/\/img.mukewang.com\/55249cf30001ae8a06000338.jpg", "description":
"\u6570\u5b66\u77e5\u8bc6\u4e0eCSS\u7ed3\u5408\u5b9e\u73b0\u9177\u70ab\u6548\u679c", "learner":
45625
},{
"id":3, "name":
"Oracle\u6570\u636e\u5e93\u5f00\u53d1\u5fc5\u5907\u5229\u5668\u4e4bPL\/SQL\u57fa\u7840", "picSmall":
"http:\/\/img.mukewang.com\/5523711700016d1606000338-300-170.jpg", "picBig":
"http:\/\/img.mukewang.com\/5523711700016d1606000338.jpg", "description":
"Oracle\u6570\u636e\u5e93\u9ad8\u7ea7\u5f00\u53d1\u5fc5\u5907\u7684\u57fa\u7840\u3002", "learner":
41236
}],"msg":"\u6210\u529f"
}*/
}
@Override
public void onFailure(Call call, Throwable t) {
}
});
}
}
public interface StringInterface {
@GET(value = "api/teacher?type=4&num=3")
CallgetString();
}
3:@Path标识符的用法
public class MainActivity extends AppCompatActivity {
private Retrofit retrofit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
retrofit = new Retrofit.Builder().baseUrl("http://www.imooc.com/").addConverterFactory(ScalarsConverterFactory.create()).build();//ScalarsConverterFactory是访问字符串要用到的,需要添加compile 'com.squareup.retrofit2:converter-scalars:2.3.0'依赖
StringInterface stringInterface = retrofit.create(StringInterface.class);
Call call = stringInterface.getString("teacher");
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
Log.d("MainActivity", response.body());
/* 输出内容为:
03 - 08 21:21:34.274 7500 - 7500 / com.example.liang.lianxi D / MainActivity:{
"status":1, "data":[{
"id":1, "name":
"Tony\u8001\u5e08\u804ashell\u2014\u2014\u73af\u5883\u53d8\u91cf\u914d\u7f6e\u6587\u4ef6", "picSmall":
"http:\/\/img.mukewang.com\/55237dcc0001128c06000338-300-170.jpg", "picBig":
"http:\/\/img.mukewang.com\/55237dcc0001128c06000338.jpg", "description":
"\u4e3a\u4f60\u5e26\u6765shell\u4e2d\u7684\u73af\u5883\u53d8\u91cf\u914d\u7f6e\u6587\u4ef6", "learner":
12312
},{
"id":2, "name":
"\u6570\u5b66\u77e5\u8bc6\u5728CSS\u52a8\u753b\u4e2d\u7684\u5e94\u7528", "picSmall":
"http:\/\/img.mukewang.com\/55249cf30001ae8a06000338-300-170.jpg", "picBig":
"http:\/\/img.mukewang.com\/55249cf30001ae8a06000338.jpg", "description":
"\u6570\u5b66\u77e5\u8bc6\u4e0eCSS\u7ed3\u5408\u5b9e\u73b0\u9177\u70ab\u6548\u679c", "learner":
45625
},{
"id":3, "name":
"Oracle\u6570\u636e\u5e93\u5f00\u53d1\u5fc5\u5907\u5229\u5668\u4e4bPL\/SQL\u57fa\u7840", "picSmall":
"http:\/\/img.mukewang.com\/5523711700016d1606000338-300-170.jpg", "picBig":
"http:\/\/img.mukewang.com\/5523711700016d1606000338.jpg", "description":
"Oracle\u6570\u636e\u5e93\u9ad8\u7ea7\u5f00\u53d1\u5fc5\u5907\u7684\u57fa\u7840\u3002", "learner":
41236
}],"msg":"\u6210\u529f"
}*/
}
@Override
public void onFailure(Call call, Throwable t) {
}
});
}
}
public interface StringInterface {
@GET(value = "api/{laoshi}?type=4&num=3")
CallgetString(@Path(value = "laoshi")String canshu);//和上一个例子的不同之处就在这里,其他一样
}
4:@QueryMap标识符的使用
public class MainActivity extends AppCompatActivity {
private Retrofit retrofit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
retrofit = new Retrofit.Builder().baseUrl("http://www.imooc.com/").addConverterFactory(ScalarsConverterFactory.create()).build();//ScalarsConverterFactory是访问字符串要用到的,需要添加compile 'com.squareup.retrofit2:converter-scalars:2.3.0'依赖
StringInterface stringInterface = retrofit.create(StringInterface.class);
Mapmap=new ArrayMap<>();
map.put("type","4");
map.put("num","3");
Call call = stringInterface.getString("teacher",map);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
Log.d("MainActivity", response.body());
/* 输出内容为:
03 - 08 21:21:34.274 7500 - 7500 / com.example.liang.lianxi D / MainActivity:{
"status":1, "data":[{
"id":1, "name":
"Tony\u8001\u5e08\u804ashell\u2014\u2014\u73af\u5883\u53d8\u91cf\u914d\u7f6e\u6587\u4ef6", "picSmall":
"http:\/\/img.mukewang.com\/55237dcc0001128c06000338-300-170.jpg", "picBig":
"http:\/\/img.mukewang.com\/55237dcc0001128c06000338.jpg", "description":
"\u4e3a\u4f60\u5e26\u6765shell\u4e2d\u7684\u73af\u5883\u53d8\u91cf\u914d\u7f6e\u6587\u4ef6", "learner":
12312
},{
"id":2, "name":
"\u6570\u5b66\u77e5\u8bc6\u5728CSS\u52a8\u753b\u4e2d\u7684\u5e94\u7528", "picSmall":
"http:\/\/img.mukewang.com\/55249cf30001ae8a06000338-300-170.jpg", "picBig":
"http:\/\/img.mukewang.com\/55249cf30001ae8a06000338.jpg", "description":
"\u6570\u5b66\u77e5\u8bc6\u4e0eCSS\u7ed3\u5408\u5b9e\u73b0\u9177\u70ab\u6548\u679c", "learner":
45625
},{
"id":3, "name":
"Oracle\u6570\u636e\u5e93\u5f00\u53d1\u5fc5\u5907\u5229\u5668\u4e4bPL\/SQL\u57fa\u7840", "picSmall":
"http:\/\/img.mukewang.com\/5523711700016d1606000338-300-170.jpg", "picBig":
"http:\/\/img.mukewang.com\/5523711700016d1606000338.jpg", "description":
"Oracle\u6570\u636e\u5e93\u9ad8\u7ea7\u5f00\u53d1\u5fc5\u5907\u7684\u57fa\u7840\u3002", "learner":
41236
}],"msg":"\u6210\u529f"
}*/
}
@Override
public void onFailure(Call call, Throwable t) {
}
});
}
}
public interface StringInterface {
@GET(value = "api/{laoshi}")
CallgetString(@Path(value = "laoshi")String canshu, @QueryMap() Mapmap);//和上一个例子的不同之处就在这里,其他一样,多个标识符可以结合使用
}
5:通过post的方式获取一个网页的内容,其中用到了 @FormUrlEncoded,@POST,@Field标识符
public class MainActivity extends AppCompatActivity {
private Retrofit retrofit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
retrofit = new Retrofit.Builder().baseUrl("http://39.107.104.102:8080/").addConverterFactory(ScalarsConverterFactory.create()).build();//ScalarsConverterFactory是访问字符串要用到的,需要添加compile 'com.squareup.retrofit2:converter-scalars:2.3.0'依赖
StringInterface stringInterface = retrofit.create(StringInterface.class);
Call call = stringInterface.getString("我是测试");
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
Log.d("MainActivity", response.body());
/* 输出内容为:
03-08 23:06:25.284 6669-6669/com.example.liang.lianxi D/MainActivity: 你发送过来的值是我是测试
*/
}
@Override
public void onFailure(Call call, Throwable t) {
}
});
}
}
public interface StringInterface {
@FormUrlEncoded
@POST(value = "retrofitceshi.jsp")
CallgetString(@Field("ceshi")String zhi);//和上一个例子的不同之处就在这里,其他一样
}
6:@Headers标识符的用法,静态添加head,获取请求头
public class MainActivity extends AppCompatActivity {
private Retrofit retrofit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
retrofit = new Retrofit.Builder().baseUrl("http://39.107.104.102:8080/").addConverterFactory(ScalarsConverterFactory.create()).build();//ScalarsConverterFactory是访问字符串要用到的,需要添加compile 'com.squareup.retrofit2:converter-scalars:2.3.0'依赖
StringInterface stringInterface = retrofit.create(StringInterface.class);
Call call = stringInterface.getString("我是测试");
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
Log.d("MainActivity", response.body());
/* 输出内容为:
03-10 22:43:08.823 31450-31450/com.example.liang.lianxi D/MainActivity: 你发送过来的值是我是测试,你的head为:woshitou
*/
}
@Override
public void onFailure(Call call, Throwable t) {
}
});
}
}
public interface StringInterface {
@Headers(value = "head:woshitou")//多加的,静态添加head
@FormUrlEncoded
@POST(value = "retrofitceshi.jsp")
CallgetString(@Field("ceshi")String zhi);
}
7:@Header标识符的用法,动态添加head的方法
public class MainActivity extends AppCompatActivity {
private Retrofit retrofit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
retrofit = new Retrofit.Builder().baseUrl("http://39.107.104.102:8080/").addConverterFactory(ScalarsConverterFactory.create()).build();//ScalarsConverterFactory是访问字符串要用到的,需要添加compile 'com.squareup.retrofit2:converter-scalars:2.3.0'依赖
StringInterface stringInterface = retrofit.create(StringInterface.class);
Call call = stringInterface.getString("我是测试","woshidongtaihead");
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
Log.d("MainActivity", response.body());
/* 输出内容为:
03-10 22:55:12.753 19564-19564/com.example.liang.lianxi D/MainActivity: 你发送过来的值是我是测试,你的head为:woshidongtaihead
*/
}
@Override
public void onFailure(Call call, Throwable t) {
}
});
}
}
public interface StringInterface {
@FormUrlEncoded
@POST(value = "retrofitceshi.jsp")
CallgetString(@Field("ceshi")String zhi, @Header("head")String tou);
}
8:通过@Multipart和@Part实现文件的上传
public class MainActivity extends AppCompatActivity {
private Retrofit retrofit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
applyPermissions(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
setContentView(R.layout.activity_main);
RequestBody requestBody=RequestBody.create(MediaType.parse("multipart/form-data"),new File("/storage/emulated/0/1.png"));
MultipartBody.Part part=MultipartBody.Part.createFormData("xieyi","ceshi.png",requestBody);
String descriptionString = "hello, 这是文件描述";
RequestBody description = RequestBody.create(MediaType.parse("multipart/form-data"), descriptionString);
retrofit = new Retrofit.Builder().baseUrl("http://39.107.104.102:8080/").build();
FileUploadService fileUploadService=retrofit.create(FileUploadService.class);
Callcall=fileUploadService.upload(description,part);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
Log.d("MainActivity", "成功");
}
@Override
public void onFailure(Call call, Throwable t) {
Log.d("MainActivity", "失败");
}
});
}
public void applyPermissions(Context context, String permission){//参数permission:Manifest.permission.CALL_PHONE
if(ContextCompat.checkSelfPermission(context, permission)!= PackageManager.PERMISSION_GRANTED)//checkSelfPermission返回的结果如果是0表示同意,1表示禁止
{
ActivityCompat.requestPermissions((Activity) context,new String[]{permission},1);//当调用requestPermissions时,系统会自动创建一个对话框
}else {
}
}
}
public interface FileUploadService {
@Multipart
@POST("uploadtouxiang.jsp")
Call upload(@Part("description") RequestBody description, @Part MultipartBody.Part file);
}
9:下面这个例子和上面那个例子一样,只是这个例子没有添加请求描述
public class MainActivity extends AppCompatActivity {
private Retrofit retrofit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
applyPermissions(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
setContentView(R.layout.activity_main);
RequestBody requestBody=RequestBody.create(MediaType.parse("multipart/form-data"),new File("/storage/emulated/0/1.png"));
MultipartBody.Part part=MultipartBody.Part.createFormData("xieyi","ceshi.png",requestBody);
retrofit = new Retrofit.Builder().baseUrl("http://39.107.104.102:8080/").build();
FileUploadService fileUploadService=retrofit.create(FileUploadService.class);
Callcall=fileUploadService.upload(part);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
Log.d("MainActivity", "成功");
}
@Override
public void onFailure(Call call, Throwable t) {
Log.d("MainActivity", "失败");
}
});
}
public void applyPermissions(Context context, String permission){//参数permission:Manifest.permission.CALL_PHONE
if(ContextCompat.checkSelfPermission(context, permission)!= PackageManager.PERMISSION_GRANTED)//checkSelfPermission返回的结果如果是0表示同意,1表示禁止
{
ActivityCompat.requestPermissions((Activity) context,new String[]{permission},1);//当调用requestPermissions时,系统会自动创建一个对话框
}else {
}
}
}
public interface FileUploadService {
@Multipart
@POST("uploadtouxiang.jsp")
Call upload(@Part MultipartBody.Part file);
}
10:retrofit与rxjava的结合
首先需要添加rxjava的依赖如下
compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
//注意当添加了这个依赖后,相当于添加了rxjava2这个库
示例代码如下:
Retrofit retrofit=new Retrofit.Builder().baseUrl("http://www.imooc.com/api/")
.addConverterFactory(ScalarsConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())//通过addCallAdapterFactory添加rxjava2的调用适配器工厂
.build();
StringInterface stringInterface=retrofit.create(StringInterface.class);
stringInterface.get(4).subscribeOn(Schedulers.newThread()).subscribe(new Consumer() {
@Override
public void accept(String s) throws Exception {
Log.d("MainActivity", s);
}
});
public interface StringInterface {
@GET(value = "teacher?type=4")
Observable get(@Query(value = "num")int n);
}
注意:像上面的这种情况最后我们无法获取到返回的Header和响应码的,如果我们需要这两者,提供两种方案:
1、用Observable
2、用Observable
Result代码如下所示,Response同理:
Retrofit retrofit=new Retrofit.Builder().baseUrl("http://www.imooc.com/api/")
.addConverterFactory(ScalarsConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
StringInterface stringInterface=retrofit.create(StringInterface.class);
stringInterface.get(4).subscribeOn(Schedulers.newThread()).subscribe(new Consumer>() {
@Override
public void accept(Result s) throws Exception {
Log.d("MainActivity", s.response().message()+","+s.response().headers()+","+s.response().body());
}
});
public interface StringInterface {
@GET(value = "teacher?type=4")
Observable> get(@Query(value = "num")int n);
}
11:Retrofit的Url组合规则
如果你在注解中提供的url是完整的url,则url将作为请求的url。
如果你在注解中提供的url是不完整的url,且不以 / 开头,则请求的url为baseUrl+注解中提供的值
如果你在注解中提供的url是不完整的url,且以 / 开头,则请求的url为baseUrl的主机部分+注解中提供的值
12: Retrofit提供的Converter
Converter Gradle依赖
Gson com.squareup.retrofit2:converter-gson:2.0.2
Jackson com.squareup.retrofit2:converter-jackson:2.0.2
Moshi com.squareup.retrofit2:converter-moshi:2.0.2
Protobuf com.squareup.retrofit2:converter-protobuf:2.0.2
Wire com.squareup.retrofit2:converter-wire:2.0.2
Simple XML com.squareup.retrofit2:converter-simplexml:2.0.2
Scalars com.squareup.retrofit2:converter-scalars:2.0.2
13: Retrofit提供的CallAdapter:
CallAdapter Gradle依赖
guava com.squareup.retrofit2:adapter-guava:2.0.2
Java8 com.squareup.retrofit2:adapter-java8:2.0.2
rxjava com.squareup.retrofit2:adapter-rxjava:2.0.2
参考文章如下:
你真的会用Retrofit2吗?Retrofit2完全教程