Retrofit+Okhhtp框架使用心得

  使用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" ; 
2、創建ServiceApi類
public class ServiceApi {


//(沒有參數)
    public interface bannerImage{
        @POST(UrlUtils.BANNER) // 
@POST(這裏面放的是url)
這裏的url爲B;注意:不能以“/”爲開頭        		Call<NewsImageBean> getNewsImage();
 }
//有參數
    public  interface homeSign{
        @POST(UrlUtils.HOMETOTAL)
        Call<HomeTotalBean> getHomeSign(@Body RequestBody body); //括號裏面放的是參數,由於我這個公司後臺要的參數是以json字符串形式,所有通過這個RequestBody轉換成json字符串

    }
} RequestBody:
/**
 * 將參數轉化成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請求,還有一些小注意的可以問問度娘,會了這些,做項目時網絡請求就沒問題了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章