1、首先添加下方依赖(包含Gson依赖)
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
2、做一个回调接口类
public interface CallBack {
void onSuccess(Object o);
void onFailed(Throwable t);
}
3、创建一个接口类负责拼接公共参数
package com.example.week1demo2.utils;
import com.example.week1demo2.bean.Bean;
import java.util.Map;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.QueryMap;
public interface ApiService {
//http://result.eolinker.com/umIPmfS6c83237d9c70c7c9510c9b0f97171a308d13b611?uri=homepage
@GET("umIPmfS6c83237d9c70c7c9510c9b0f97171a308d13b611")
Call<Bean> getGoods(@QueryMap Map<String, String> map);
}
4、工具类(包含单例模式)
package com.example.week1demo2.utils;
import com.example.week1demo2.bean.Bean;
import java.util.Map;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitUtils {
private static volatile RetrofitUtils instance;
public static RetrofitUtils getInstance(){
if (instance==null){
synchronized (RetrofitUtils.class){
if (instance==null){
instance=new RetrofitUtils();
}
}
}
return instance;
}
public void getNews(String baseurl, final CallBack callBack, Map map){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseurl)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService apiService = retrofit.create(ApiService.class);
Call<Bean> call = apiService.getGoods(map);
call.enqueue(new Callback<Bean>() {
@Override
public void onResponse(Call<Bean> call, Response<Bean> response) {
Bean body = response.body();
callBack.onSuccess(body);
}
@Override
public void onFailure(Call<Bean> call, Throwable t) {
callBack.onFailed(t);
}
});
}
}
5、在V层的使用(通过new P层类的时候把下面两个参数传到P层类)
hashMap.put("uri","homepage"); //公共参数后拼接用的键值对参数
url = "http://result.eolinker.com/"; //网址头
6、在P层的使用(通过V层把参数传过来之后,在把参数传到M层获取数据)
7、在M层的使用方法
package com.example.week1demo2;
import com.example.week1demo2.bean.Bean;
import com.example.week1demo2.utils.CallBack;
import com.example.week1demo2.utils.RetrofitUtils;
import java.util.Map;
/**
* Created by 墨鸦 on 2017/12/31.
*/
public class Show_m {
public void getData(String url, Map<String, String> map, final Show_p show_p){
RetrofitUtils.getInstance().getNews(url, new CallBack() {
@Override
public void onSuccess(Object o) {
Bean bean = (Bean) o; //这是请求到的数据
show_p.showSuccess(bean);
}
@Override
public void onFailed(Throwable t) {
show_p.showFailed();
}
},map);
}
}