使用Retrofit+Okhttp已经完成一个项目,现在总结一下我在项目中使用retrofit这个框架的经验,绝对值得一看(项目中全部都是POST请求)
1、先写url:A+B=完整的url;
A:public static final String SERVICE = "http://192.168.1.147:8080/jgjr/"
B:
public static final String BANNER = "banner/newsImg" ;
public class ServiceApi { //(没有参数) public interface bannerImage{ @POST(UrlUtils.BANNER) //RequestBody:@POST(这里面放的是url)这里的url为B;注意:不能以“/”为开头 Call<NewsImageBean> getNewsImage();}//有参数 public interface homeSign{ @POST(UrlUtils.HOMETOTAL) Call<HomeTotalBean> getHomeSign(@Body RequestBody body); //括号里面放的是参数,由于我这个公司后台要的参数是以json字符串形式,所有通过这个RequestBody转换成json字符串}}
/** * 将参数转化成json字符串提交到后台 * @param maps * @return */ public static RequestBody getBody(Map<String, Object> maps) { Gson gson = new Gson(); String json = gson.toJson(maps); MediaType JSON = MediaType.parse("application/json; charset=utf-8"); RequestBody body = RequestBody.create(JSON, json); return body; }3、获取Retrofit对象
public static Retrofit getRetrofit() { Retrofit retrofit = new Retrofit.Builder() .baseUrl(UrlUtils.SERVICE) //这里的url为A 注意:这个里面是以“/”为结尾 .addConverterFactory(GsonConverterFactory.create()) .build(); return retrofit; }4、在代码中请求(以有参数为例)
ServiceApi.homeSign homeSign = retrofits.create(ServiceApi.homeSign.class) Map<String,Object> map = new HashMap(); map.put("key",value); RequestBody body = getBody(map);//传递参数(如实没有参数黄色字体可以忽略) Call<HomeTotalBean> signBeanCall = homeSign.getHomeSign(body); signBeanCall.enqueue(new Callback<HomeSignBean>() { @Override public void onResponse(Call<HomeSignBean> call, Response<HomeSignBean> response) { HomeSignBean hsb = response.body(); } @Override public void onFailure(Call<HomeSignBean> call, Throwable t) { MyPublic.showInfo(act); } });4、我公司登录时是管理cookie的
a、获取cookie
package com.xctz.niceman.jianguolicai.utils; import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import android.util.Log; import java.io.IOException; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; /** * Created by LuanXianSheng on 2016/10/9. * 捕获到cookie并将其保存到本地 */ public class SaveCookiesInterceptor implements Interceptor { private static final String COOKIE_PREF = "cookies_prefs"; private Context mContext; public SaveCookiesInterceptor(Context context) { mContext = context; } @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Response response = chain.proceed(request); //set-cookie可能为多个 if (!response.headers("set-cookie").isEmpty()) { List<String> cookies = response.headers("set-cookie"); String cookie = encodeCookie(cookies); saveCookie(request.url().toString(),request.url().host(),cookie); } return response; } //整合cookie为唯一字符串 private String encodeCookie(List<String> cookies) { StringBuilder sb = new StringBuilder(); Set<String> set=new HashSet<>(); for (String cookie : cookies) { String[] arr = cookie.split(";"); for (String s : arr) { if(set.contains(s))continue; set.add(s); } } Iterator<String> ite = set.iterator(); while (ite.hasNext()) { String cookie = ite.next(); sb.append(cookie).append(";"); } int last = sb.lastIndexOf(";"); if (sb.length() - 1 == last) { sb.deleteCharAt(last); } return sb.toString(); } //保存cookie到本地,这里我们分别为该url和host设置相同的cookie,其中host可选 //这样能使得该cookie的应用范围更广 private void saveCookie(String url,String domain,String cookies) { Log.i("Log","cookies:"+cookies) ; SharedPreferences sp = mContext.getSharedPreferences(COOKIE_PREF, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); if (TextUtils.isEmpty(url)) { throw new NullPointerException("url is null."); }else{ editor.putString(url, cookies); } if (!TextUtils.isEmpty(domain)) { editor.putString(domain, cookies); } editor.apply(); editor.commit(); } }b、将cookie添加到请求中
package com.xctz.niceman.jianguolicai.utils; import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import java.io.IOException; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; /** * Created by LuanXianSheng on 2016/10/9. * 从本地获取到cookie并将其设置到请求头里面 */ public class AddCookiesInterceptor implements Interceptor { private static final String COOKIE_PREF = "cookies_prefs"; private Context mContext; public AddCookiesInterceptor(Context context) { mContext = context; } @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Request.Builder builder = request.newBuilder(); String cookie = getCookie(request.url().toString(), request.url().host()); if (!TextUtils.isEmpty(cookie)) { builder.addHeader("Cookie", cookie); } return chain.proceed(builder.build()); } private String getCookie(String url, String domain) { SharedPreferences sp = mContext.getSharedPreferences(COOKIE_PREF, Context.MODE_PRIVATE); if (!TextUtils.isEmpty(url)&&sp.contains(url)&&!TextUtils.isEmpty(sp.getString(url,""))) { return sp.getString(url, ""); } if (!TextUtils.isEmpty(domain)&&sp.contains(domain) && !TextUtils.isEmpty(sp.getString(domain, ""))) { return sp.getString(domain, ""); } return null; } }c、在登陆后需要传递cookie时(注意的是在登录的时候SavaCookieInterceptor与AddCookieInterceptor这两个全部都得加入到OkHttpClient中):
/** * 这个方法为登录时的操作(就是需要cookie) * @return */ public static Retrofit getCookieRetrofit(Context context){ OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(new AddCookiesInterceptor(context)) .build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(UrlUtils.SERVICE) .addConverterFactory(GsonConverterFactory.create()) .client(client) .build(); return retrofit; }5、正常会以上的操作在数据请求中就应该没有什么问题了,现在在做上传图片的功能
//用户更换头像 public interface updateIMG{ @Multipart @POST(UrlUtils.UPDATEIMG) //下面的file为与后台索要的参数 Call<PhoneCodeBean> changIcon(@Part("fileName") String description,@Part("file\"; filename=\"usericon.jpg") RequestBody imgs); }
在代码中请求
从相册或者相机中获取图片资源省略 //开始上传头像 RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), iconfile); String name = iconfile.getName() ; Retrofit retrofit = MyPublic.getCookieRetrofit(act) ;//这个是获取到带有cookie的retrofit实例 ServiceApi.updateIMG image = retrofit.create(ServiceApi.updateIMG.class) ; Call<PhoneCodeBean> imageCall = image.changIcon(name,body) ; imageCall.enqueue(new Callback<PhoneCodeBean>() { @Override public void onResponse(Call<PhoneCodeBean> call, Response<PhoneCodeBean> response) { PhoneCodeBean bean = response.body() ; ubean.setFaceImg(bean.getMessage()); db.update(ubean,ubean.getUserID()); ImageLoader.getInstance().displayImage(ubean.getFaceImg(), mineHeadicon); } @Override public void onFailure(Call<PhoneCodeBean> call, Throwable t) { } }); }OK了,以上就是我使用的Retrofit的总结,当然,整个项目中只是用了POST请求,还有一些小注意的可以问问度娘,会了这些,做项目时网络请求就没问题了