Retrofit是okhttp的进化版,是okhttp网络框架的升级,是目前最具潮流的网络请求框架,运用注解和动态代理模式,极大的简化了网络请求的繁琐步骤
Retrofit与OKhttp的不同:
- 1.设置请求方式是注解的形式
- 2.接口拼接字符串更灵活 (BaseUEL以"/“结尾, 注解的URL一定不要以”/"开头)
- 3.异步响应回调方法在主线程
Retrofit GET请求
public class Constant {
//baseurl
public final static String URL_BASE = "http://m2.qiushibaike.com/";
//通过动态代理模式进行网址的拼接
public interface MyServerInterface {
///////////////////////////////////////////////////GET网络请求方式//////////////////////////////////////
/**
* A.
* GET请求,指定Path参数和Query参数
* 其中注解中的变量用{ 变量名自定义 } 在方法参数中
* 格式:@Path("上面定义的变量名") 类型 定义的变量名 作用:替换url地址中"{"和"}"所包括的部分
* 格式:@Query("参数名") 类型 定义的参数名 作用:会拼接在URL的最后部分,类似追加了"page = 1"的字符串,形成提交给服务器端的请求参数
*/
@GET("article/list/{type}?")
Call<QiushiModel> getInfoList(@Path("type") String type, @Query("page") int page);
//新建retrofit
Retrofit build = new Retrofit.Builder()
.baseUrl(Urls.path)
.build();
Methods methods = build.create(Methods.class);
//调用接口中的抽象方法
Call<ResponseBody> instance = methods.getInstance();
instance.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
try {
//回调在主线程
String string = response.body().string();
tv.setText(string);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable t) {
}
});
}