網(wǎng)絡(luò)框架-Retrofit(二)

Xml格式配置
<root>
<user userid = '1' name='kpioneer'> 你好,我是kpioneer</user>
<user userid = '2' name='Jeason'> 你好,我是Jeason</user>
<user userid = '3' name='Cookie'> 你好,我是Cook</user>
</root>

注意:@Root:注解代表Xml根節(jié)點(diǎn)(需要在類(lèi)上面使用)
例如:<root></root>

      @Element:注解代表根節(jié)點(diǎn)中下面子節(jié)點(diǎn)
       例如:<user></user>
       
      @Attribute:注解代表標(biāo)簽頁(yè)中的屬性
       例如:userid = '1'
          
      @Text:注解代表標(biāo)簽內(nèi)容
       例如:你好,我是kpioneer

解析器源碼:

.addConverterFactory(xxxxFactory.create())
采用抽象工廠模式
抽象工廠模式是工廠方法模式的進(jìn)一步延伸,由于它提供了功能更為強(qiáng)大的工廠類(lèi)并且具備較好的可擴(kuò)展性

public interface Converter<F, T> {
  T convert(F value) throws IOException;

  /** Creates {@link Converter} instances based on a type and target usage. */
  abstract class Factory {
    /**
     * Returns a {@link Converter} for converting an HTTP response body to {@code type}, or null if
     * {@code type} cannot be handled by this factory. This is used to create converters for
     * response types such as {@code SimpleResponse} from a {@code Call<SimpleResponse>}
     * declaration.
     */
    public @Nullable Converter<ResponseBody, ?> responseBodyConverter(Type type,
        Annotation[] annotations, Retrofit retrofit) {
      return null;
    }

    /**
     * Returns a {@link Converter} for converting {@code type} to an HTTP request body, or null if
     * {@code type} cannot be handled by this factory. This is used to create converters for types
     * specified by {@link Body @Body}, {@link Part @Part}, and {@link PartMap @PartMap}
     * values.
     */
    public @Nullable Converter<?, RequestBody> requestBodyConverter(Type type,
        Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
      return null;
    }

    /**
     * Returns a {@link Converter} for converting {@code type} to a {@link String}, or null if
     * {@code type} cannot be handled by this factory. This is used to create converters for types
     * specified by {@link Field @Field}, {@link FieldMap @FieldMap} values,
     * {@link Header @Header}, {@link HeaderMap @HeaderMap}, {@link Path @Path},
     * {@link Query @Query}, and {@link QueryMap @QueryMap} values.
     */
    public @Nullable Converter<?, String> stringConverter(Type type, Annotation[] annotations,
        Retrofit retrofit) {
      return null;
    }

    /**
     * Extract the upper bound of the generic parameter at {@code index} from {@code type}. For
     * example, index 1 of {@code Map<String, ? extends Runnable>} returns {@code Runnable}.
     */
    protected static Type getParameterUpperBound(int index, ParameterizedType type) {
      return Utils.getParameterUpperBound(index, type);
    }

    /**
     * Extract the raw class type from {@code type}. For example, the type representing
     * {@code List<? extends Runnable>} returns {@code List.class}.
     */
    protected static Class<?> getRawType(Type type) {
      return Utils.getRawType(type);
    }
  }
}

簡(jiǎn)單區(qū)分:
抽象工廠模式:一組相關(guān)性很高的方法
工廠方法模式:一個(gè)方法

Retrofit框架+RxJava開(kāi)發(fā)
配置RxJava環(huán)境

    compile 'io.reactivex:rxjava:1.3.0'
    compile 'io.reactivex:rxandroid:1.2.1'
public interface RxJavaLoginService {
    @FormUrlEncoded
    @POST("user/login?platform=android&city_id=101&type=pwd&channel=baiduxi&version=3.2.0&os_version=6.0.1&device_id=866622020797175")
    public Observable<LoginBean> login(@Field("mobile") String username, @Field("password")String password);
}
public class SimpleRetrofitRxJava {
    private static String URL_SERVER = "http://api.cloud.test.haocaisong.cn/v2.0/";

    /**
     * 異步:采用Retrofit框架自帶的
     *
     * @param username
     * @param password
     * @param onHttpResultListener
     */
    public static void login(String username, String password, final SimpleSystemLogin.OnHttpResultListener onHttpResultListener) {
        RxJavaLoginService loginService = getLoginService();
        loginService.login(username, password).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<LoginBean>() {

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(LoginBean loginBean) {
                        onHttpResultListener.onHttpResult(loginBean.getErrmsg());
                    }
                });


//        try {
//            callLogin.enqueue(new Callback<LoginBean>() {
//                @Override
//                public void onResponse(Call<LoginBean> call, Response<LoginBean> response) {
//                    onHttpResultListener.onHttpResult(response.body());
//                }
//
//                @Override
//                public void onFailure(Call<LoginBean> call, Throwable t) {
//                    onHttpResultListener.onHttpResult("登錄失敗!");
//                }
//            });
//        }catch (Exception e){
//            e.printStackTrace();
//        }

    }

    @NonNull
    private static OkHttpClient getOkHttpClient() {
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        return new OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor).build();
    }

    private static RxJavaLoginService getLoginService() {
        OkHttpClient okHttpClient = getOkHttpClient();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(URL_SERVER)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(okHttpClient)
                .build();
        return retrofit.create(RxJavaLoginService.class);
    }
}

核心代碼分析:
動(dòng)態(tài)代理和注解方式實(shí)現(xiàn)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌掉冶,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,807評(píng)論 6 518
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異辞做,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)寡具,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,284評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門(mén)秤茅,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人童叠,你說(shuō)我怎么就攤上這事框喳。” “怎么了厦坛?”我有些...
    開(kāi)封第一講書(shū)人閱讀 169,589評(píng)論 0 363
  • 文/不壞的土叔 我叫張陵五垮,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我杜秸,道長(zhǎng)放仗,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 60,188評(píng)論 1 300
  • 正文 為了忘掉前任撬碟,我火速辦了婚禮诞挨,結(jié)果婚禮上莉撇,老公的妹妹穿的比我還像新娘。我一直安慰自己惶傻,他們只是感情好棍郎,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,185評(píng)論 6 398
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著银室,像睡著了一般涂佃。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上粮揉,一...
    開(kāi)封第一講書(shū)人閱讀 52,785評(píng)論 1 314
  • 那天巡李,我揣著相機(jī)與錄音,去河邊找鬼扶认。 笑死侨拦,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的辐宾。 我是一名探鬼主播狱从,決...
    沈念sama閱讀 41,220評(píng)論 3 423
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼叠纹!你這毒婦竟也來(lái)了季研?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 40,167評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤誉察,失蹤者是張志新(化名)和其女友劉穎与涡,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體持偏,經(jīng)...
    沈念sama閱讀 46,698評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡驼卖,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,767評(píng)論 3 343
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了鸿秆。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片酌畜。...
    茶點(diǎn)故事閱讀 40,912評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖卿叽,靈堂內(nèi)的尸體忽然破棺而出桥胞,到底是詐尸還是另有隱情,我是刑警寧澤考婴,帶...
    沈念sama閱讀 36,572評(píng)論 5 351
  • 正文 年R本政府宣布贩虾,位于F島的核電站,受9級(jí)特大地震影響沥阱,放射性物質(zhì)發(fā)生泄漏整胃。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,254評(píng)論 3 336
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望屁使。 院中可真熱鬧在岂,春花似錦、人聲如沸蛮寂。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,746評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)酬蹋。三九已至及老,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間范抓,已是汗流浹背骄恶。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,859評(píng)論 1 274
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留匕垫,地道東北人僧鲁。 一個(gè)月前我還...
    沈念sama閱讀 49,359評(píng)論 3 379
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像象泵,于是被迫代替她去往敵國(guó)和親寞秃。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,922評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,332評(píng)論 25 707
  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理偶惠,服務(wù)發(fā)現(xiàn)春寿,斷路器,智...
    卡卡羅2017閱讀 134,716評(píng)論 18 139
  • 我們的一言一行,我們的工作兄一、生活與社交绢淀,無(wú)時(shí)無(wú)刻不在進(jìn)行自我推銷(xiāo)。關(guān)鍵在于你是以一個(gè)好的面貌與狀態(tài)出現(xiàn)在人前瘾腰,還是...
    好聽(tīng)的暖陽(yáng)閱讀 221評(píng)論 0 4
  • 一直只知道劉同的《青茫》三部曲(《誰(shuí)的青春不迷酶猜模》蹋盆,《你的孤獨(dú),雖敗猶榮》硝全,《向著光亮那方》)栖雾。今天偶然的機(jī)會(huì)...
    追風(fēng)箏的孩子奔跑在天邊閱讀 303評(píng)論 0 0