一,导入依赖
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4' compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'
二,创建接口类
public class Api { //http://120.27.23.105/product/getCatagory public final static String string1 = "http://120.27.23.105"; public final static String string2 = "/product/getCatagory"; }
三,请求原始数据,搭建Bean类
四,创建接口用来获取数据和回调数据
public interface Service { //把接口穿进去,先只传路径 @GET(Api.string2) //回调数据的接口,泛型为接口Bean类,方法名。 Call<Bean> getData(); }
五,Activity
public class MainActivity extends AppCompatActivity { private Retrofit retrofit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //创建Retrofit对象 Retrofit retrofit = new Retrofit.Builder() //这里填接口的域名(接口上半部分) .baseUrl(Api.string1) //调用Retrofit自己的解析方法,包含了Gson .addConverterFactory(GsonConverterFactory.create()) .build(); //拿到定义好的接口类 Service service = retrofit.create(Service.class); //拿到回调的数据 Call<Bean> data = service.getData(); //使用异步请求方式 data.enqueue(new Callback<Bean>() { @Override public void onResponse(Call<Bean> call, Response<Bean> response) { Toast.makeText(MainActivity.this, "成功", Toast.LENGTH_SHORT).show(); } @Override public void onFailure(Call<Bean> call, Throwable t) { Toast.makeText(MainActivity.this, "失败", Toast.LENGTH_SHORT).show(); } }); } }