RetrofitDemo

来源:互联网 发布:修改linux运行级别 编辑:程序博客网 时间:2024/04/29 16:20

Retrofit Demo

编写了一个最简单的Demo:

三种功能:

1、普通GET请求 获取Ip地址与经纬度   ,返回JSon数据由Gson解析为对象;

2、带参数的GET请求 根据经纬度定位周边基站,返回JSon数据由Gson解析List<Object>;

3、POST请求 返回Json数据 不用Gson解析,直接打印

 

Tips

1、网络上的例子一般都是直接将Json数据转为对象,找了好久才知道可以用ResponseBody获取Json字符串 arg0.body().string();

2、Post方法 添加 表单时 要加@FormUrlEncoded,否则会报错  @Field parameters can only be used with formencoding. (parameter #1)

3、返回的JSon不是数组时不可以用List

 

ApiService:代码 

RetrofitService :三个网络请求接口

importjava.util.List;
import retrofit.Call;
import retrofit.http.Field;
import retrofit.http.FormUrlEncoded;
import retrofit.http.GET;
import retrofit.http.POST;
import retrofit.http.Path;
import retrofit.http.Query;
import bean.CellMode;
import bean.LocationMode;
import com.squareup.okhttp.ResponseBody;

public interface RetrofitService {
         //获取IP地址及定
         @POST("H_HDJAD_IP/servlet/IpLocationServlet")
          
Call<LocationMode> getIpLoc();
         //反向基站定位
         @GET("/recell")
         Call<List<CellMode>>getcell(@Query("lat") String lat,@Query("lon") String lon);
         //
上传基站信息
         @FormUrlEncoded
         @POST("/CellCollection/servlet/CellCollectionServlet")
         Call<ResponseBody>postCell(@Field("address") String address,@Field("result")String result)
;
}

RetrofitServiceGeter  :获取接口Interface

importjava.util.concurrent.TimeUnit;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit;
import com.squareup.okhttp.OkHttpClient;
import config.ConstantsConfig;

public class RetrofitServiceGeter {
         static RetrofitServiceretrofitService =null;
         public static RetrofitServicegetRetrofitService(String url,boolean convert){
//                 if(retrofitService==null){
                            OkHttpClientclient = new OkHttpClient();
                            client.setConnectTimeout(ConstantsConfig.NET_CONNECT_TIME_OUT_TIME,TimeUnit.SECONDS);
                            client.setWriteTimeout(ConstantsConfig.NET_WRITE_TIME_OUT_TIME,TimeUnit.SECONDS);
                            client.setReadTimeout(ConstantsConfig.NET_READ_TIME_OUT_TIME,TimeUnit.SECONDS);
                            Retrofit.Builderbuilder = new Retrofit.Builder();
                            builder.client(client);
                            builder.baseUrl(url);
                            if(convert){
                                     builder.addConverterFactory(GsonConverterFactory.create());
                            }
                            Retrofitretrofit=builder.build();
                            retrofitService= retrofit.create(RetrofitService.class);
//                 }
                   return retrofitService;
         }
}

 

HttpUtil:网络请求代码

importjava.util.List;
import java.util.Map;
import com.squareup.okhttp.ResponseBody;
import config.ConstantsConfig;
import config.Logger;
import bean.CellMode;
import bean.LocationMode;
import netInterface.RetrofitService;
import netInterface.RetrofitServiceGeter;
import retrofit.Callback;
import retrofit.Response;
import retrofit.Retrofit;
public class HttpUtil {
         ResponseListenerlistener = null;;
         publicHttpUtil() {
                   //TODO Auto-generated constructor stub
         }
         publicvoid getData(Map<String, String> map , String url){
                  
         }
         /**
          * getIP
          * @param map
          * @param url
          */
         public void gettIPLoc (Map<String, String> map , String url){
                   RetrofitServiceipLocationService=RetrofitServiceGeter.getRetrofitService(url, true);
                   ipLocationService.getIpLoc().enqueue(newCallback<LocationMode>() {
                            @Override
                            publicvoid onResponse(Response<LocationMode> arg0, Retrofit arg1) {
                                     Logger.i("IPLoccode:"+arg0.code()+"  url::"+arg1.baseUrl().url());
                                     Stringurl = arg1.baseUrl().url().toString();
                                     LocationModeresult = arg0.body();
                                     LocationModelocationMode = null;
                                     if(result!=null&& result instanceof LocationMode ){
                                               locationMode= (LocationMode)result;
                                               locationMode.setUrl(url);
                                     }
                                     Logger.i("IPLocresult:"+result);
                                     if(listener!=null){//连接成功  200404  (404 result =null)
                                               if(locationMode!=null){
                                                        listener.result(locationMode);
                                               }else{
                                                        listener.result(result);
                                               }
                                     }
                            }
                            @Override
                            publicvoid onFailure(Throwable arg0) {//建立连接失败
                                     Logger.i("IPLocERROR:"+arg0.toString());
                                     listener.result(null);
                            }
                   });
         }
         /**
          * getIP
          * @param map
          * @param url
          */
         public void getReCell (Map<String, String> map){
                   RetrofitServiceipLocationService=RetrofitServiceGeter.getRetrofitService(ConstantsConfig.RECELL_BASE_URL,true);
                   ipLocationService.getcell(map.get("lat"),map.get("lon")).enqueue(new Callback<List<CellMode>>() {
                           
                            @Override
                            publicvoid onResponse(Response<List<CellMode>> arg0, Retrofit arg1) {
                                     Logger.i("GETCellcode:"+arg0.code());
                                     List<CellMode>list = arg0.body();
                                     Logger.i("GETCellResult:"+list);
                                     listener.result(list);
                            }
                            @Override
                            publicvoid onFailure(Throwable arg0) {
                                     Logger.i("GETCellERROR:"+arg0.toString());
                                     listener.result(null);
                            }
                   });
                  
         }
         public void pushCell (Map<String, String> map){
                   RetrofitServiceipLocationService=RetrofitServiceGeter.getRetrofitService(ConstantsConfig.CELL_COLLECTION,false);
                   ipLocationService.postCell(map.get("address"),map.get("result")).enqueue(new Callback<ResponseBody>() {
                           
                            @Override
                            publicvoid onResponse(Response<ResponseBody> arg0, Retrofit arg1) {
                                     try{
                                               Logger.i("PUSHCELL::"+arg0.code()+" "+arg0.body());
                                               Logger.i("PUSHCELL::"+arg0.code()+" "+arg0.body().string());
                                     }catch (Exception e) {
                                               //TODO Auto-generated catch block
                                               e.printStackTrace();
                                     }
                            }
                            @Override
                            publicvoid onFailure(Throwable arg0) {
                                     Logger.i("PUSHCELL::ERR:"+arg0.toString());
                            }
                   });
         }
         publicvoid setListener(ResponseListener listener){
                   this.listener= listener;
         }
         publicinterface ResponseListener{
                   voidresult(Object obj);
         }
}

 Demo URL :http://download.csdn.net/detail/u013151574/9600568 点击打开链接


0 0