Retrofit是Square公司开发的一款针对Android网络请求的框架,Retrofit2底层基于OkHttp实现的.来看看它的基本使用方法:
1.定义一个自定义的接口,这里需要稍作说明,@GET注解就表示get请求,@Query表示请求参数,将会以key=value的方式拼接在url后面;
其中的方法都是自定义的;
public interface NetInterFace {
//retrofit 原生的请求
@GET("/article/list/text?page=1")
Call<ResponseBody> getNetData();
// 自动解析的请求
@GET("/article/list/text?page=1")
Call<Modle> getNetDataWithModle();
@GET("/article/list/text?")
Call<Modle> getNetDataWithPage(@Query("page") String page);
/**
* 传递多个参数 注意要加一个参数的泛型
* @return
*/
@GET("/article/list/text?")
Call<Modle> getNetDataWithParams(@QueryMap Map<String ,String> map);
/**
* 动态替换路径
*/
@GET("/article/list/{path}?page=1")
Call<ResponseBody> getNetDataWithPath(@Path("path") String path);
/**
* 动态替换路径和参数
*/
@GET("/article/list/{lala}?")
Call<ResponseBody> getNetDataWithPathParams(@Path("lala")String path,@QueryMap Map<String ,String> params);
/**
* 完全和基地址无关 ,会按照你穿过来的地址去发送网络请求
* @param url
* @return
*/
@GET
Call<ResponseBody> getNetDataWithUrl(@Url String url);
/**
* retrofit 发送post请求 动态传值
* @param url
* @param username
* @param password
* @return
*/
@POST
@FormUrlEncoded
Call<ResponseBody> postNetDataWithParam(@Url String url,@Field("username")String username,@Field("pwd")String password);
@POST("{test}")
@FormUrlEncoded
Call<ResponseBody> postNetDataWithPathParmas(@Path("test") String path, @FieldMap Map<String ,String> map);
}
2.
需要创建一个Retrofit的实例,并完成相应的配置;
addConverterFactory方法表示需要用什么转换器来解析返回值,GsonConverterFactory.create()表示调用Gson库来解析json返回值,具体的下文还会做详细介绍。
//设置基地址 基地址 必须以"/" 结尾 ,经测试 得:外网是可以不加,内网需要加 ,如果 都加上,就不会有错
mRetrofit = new Retrofit.Builder().baseUrl(NetConfig.BASE_URL)
// 添加转换工厂(用于传话 String 和实现类的 ,自动帮你解析json)
.addConverterFactory(GsonConverterFactory.create()).build();
3.生成Call对象;通过自定义的接口的方法来生成.
Call在Retrofit中就是行使网络请求并处理返回值的类,调用的时候会把需要拼接的参数传递进去,:
mNetInterface = mRetrofit.create(NetInterFace.class);
Call<ResponseBody> bodyCall = mNetInterface.getNetData();
4.完成网络请求:同步或者异步请求:
如果是同步请求则该请求会在本线程中执行;
try {
bodyCall.execute();
} catch (IOException e) {
e.printStackTrace();
}
或者异步请求:
bodyCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()){
try {
// 获取body里面的内容
String string = response.body().string();
Log.d("TAG", "onResponse: string == "+string);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
其他几种请求方式如下:
Call<Modle> netDataWithModle = mNetInterface.getNetDataWithModle();
netDataWithModle.enqueue(new Callback<Modle>() {
@Override
public void onResponse(Call<Modle> call, Response<Modle> response) {
if (response.isSuccessful()){
Modle body = response.body();
Log.d("TAG", "onResponse: body" + body.toString());
}
}
@Override
public void onFailure(Call<Modle> call, Throwable t) {
}
});
或者:
Call<Modle> netDataWithPage = mNetInterface.getNetDataWithPage("1");
netDataWithPage.enqueue(new Callback<Modle>() {
@Override
public void onResponse(Call<Modle> call, Response<Modle> response) {
if (response.isSuccessful()){
Modle modle = response.body();
Log.d("TAG", "onResponse: body == "+modle.toString());
}
}
@Override
public void onFailure(Call<Modle> call, Throwable t) {
}
});
或者:
Map params = new HashMap();
params.put("page","2");
//params.put("count","2");
Call<Modle> netDataWithParams = mNetInterface.getNetDataWithParams(params);
netDataWithParams.enqueue(new Callback<Modle>() {
@Override
public void onResponse(Call<Modle> call, Response<Modle> response) {
if (response.isSuccessful()){
Modle modle = response.body();
Log.d("TAG", "onResponse: " +modle.toString());
}
}
@Override
public void onFailure(Call<Modle> call, Throwable t) {
}
});
或者:
Call<ResponseBody> pathCall = mNetInterface.getNetDataWithPath("image");
pathCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()){
try {
Log.d("TAG", "onResponse: "+response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
更多请看:
http://blog.csdn.net/duanyy1990/article/details/52139294