MainActivity
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RetrofitUtils.getRetrofitUtils().init();
findViewById(R.id.bt_banner).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
RetrofitUtils.mRetrofitUtils.getCarPost(MainActivity.this);
}
});
}
}
MainService
public interface MainService {
@GET("/product/getProductCatagory")
Call<ResponseBody> getBanner();
@GET("/product/getCarts")
Call<ResponseBody> getCar(@Query("uid") int uid);
@POST("/product/getCarts")
Call<ResponseBody> getCarPost(@QueryMap Map<String,String> map);
}
RetrofitUtils
public class RetrofitUtils {
private Retrofit mRetrofit;
//私有的构造
private RetrofitUtils(){}
public static RetrofitUtils mRetrofitUtils;
//单例模式
public static RetrofitUtils getRetrofitUtils(){
if (mRetrofitUtils==null){
mRetrofitUtils=new RetrofitUtils();
}
return mRetrofitUtils;
}
//
public void init(){
mRetrofit = new Retrofit.Builder()
.baseUrl("http://www.zhaoapi.cn/")
.build();
}
public void getBanner(final Context context){
mRetrofit.create(MainService.class).getBanner().enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
try {
String data = response.body().string();
Toast.makeText(context, "a"+data, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}
public void getCarPost(final Context context){
Map<String,String> map = new HashMap<>();
map.put("uid","71");
mRetrofit.create(MainService.class).getCarPost(map).enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
try {
String data = response.body().string();
Toast.makeText(context, "a"+data, Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}
}