首先:导入依赖:
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'
创建一个接口:
@GET("getCatagory") Call<ShopBean> getShop(); @POST("getProducts") Call<MyShop> getMyShop(@QueryMap Map<String,String> map);主代码:
package wld.bawei.com.myretrofit; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ListView; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.GsonConverterFactory; import retrofit2.Response; import retrofit2.Retrofit; public class MainActivity extends AppCompatActivity { private Call<ShopBean> shop; private ListView lv; List<MyShop.DataBean> data; private MyAdapter myAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv = (ListView) findViewById(R.id.lv);Map集合的方法:Retrofit builder = new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .baseUrl("http://120.27.23.105/product/") .build(); ShopService shopService = builder.create(ShopService.class); Map<String,String> map=new HashMap<>(); map.put("pscid","39"); map.put("page","1"); Call<MyShop> myShop = shopService.getMyShop(map); myShop.enqueue(new Callback<MyShop>() { @Override public void onResponse(Call<MyShop> call, Response<MyShop> response) { if(response.isSuccess()&&response.body()!=null){ data = response.body().getData(); myAdapter = new MyAdapter(MainActivity.this,data); lv.setAdapter(myAdapter); myAdapter.notifyDataSetChanged(); } } @Override public void onFailure(Call<MyShop> call, Throwable t) { } });普通get方法: /* Retrofit builder = new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .baseUrl("http://120.27.23.105/product/") .build(); ShopService shopService = builder.create(ShopService.class); shop = shopService.getShop(); shop.enqueue(new Callback<ShopBean>() { @Override public void onResponse(Call<ShopBean> call, Response<ShopBean> response) { if(response.isSuccess()&&response.body()!=null){ ShopBean body = response.body(); for(ShopBean.DataBean arr:body.getData()){ Log.e("aaa","aa"+arr.getName()); } } } @Override public void onFailure(Call<ShopBean> call, Throwable t) { } });*/ }
销毁 @Override protected void onStop() { super.onStop(); if(shop!=null){ shop.cancel(); } } }