1. 程式人生 > >Retrofit+Rxjava 網路請求的簡單封裝(一)(觀察者模式)

Retrofit+Rxjava 網路請求的簡單封裝(一)(觀察者模式)

我通過公司一個上線App介面來進行Retrofit+Rxjava 的簡單學習

http://x-phone.cn/api/v1.0/DeletePrivateContact

當然你直接訪問上面的url是無法獲取伺服器Json資料的,因為是需要封裝請求體,如下是在沒有封裝請求體,返回的錯誤介面

Method Not Allowed
The method is not allowed for the requested URL.

如果想對RxJava進行簡單的瞭解,可以參考我如下的博文

RxJava響應式程式設計之初級瞭解

這篇部落格就對簡單的進行Retrofit+Rxjava 簡單封裝

1、首先建立請求介面

   //http://x-phone.cn/api/v1.0/DeletePrivateContact
    interface PostClickAppInfoParameterJsonBody{
        @Headers({"Content-Type: application/json","Accept: application/json"})
        @POST("DeletePrivateContact")
        Observable<HttpResult> getJuheResult(@Body HttpRequest request);
    }

Rxjava本質主要就是非同步任務 外層構建了一個觀察者的設計模式 它更簡潔 我們呼叫api方法 幾乎看不到 方法裡面的 分執行緒資料操作 它只是利用了 一種觀察者的設計模式 來進行 主分執行緒的通訊 來進行響應操作

所以業務介面返回一個被觀察者的介面例項讓外部去實現

2、接下來看看Retrofit如何配置OkHttp的

   protected RetrofitBase(){
        retrofit = new Retrofit.Builder()
                .baseUrl(BASEURL)
                .client(client())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory
(RxJavaCallAdapterFactory.create()) .build(); } private OkHttpClient client(){ LauncherTrust launcherTrust = new LauncherTrust(); OkHttpClient okHttpClient = new OkHttpClient.Builder() .connectTimeout(TIMEOUT, TimeUnit.MILLISECONDS) .readTimeout(TIMEOUT,TimeUnit.MILLISECONDS) .sslSocketFactory(sslSocketFactory(launcherTrust),launcherTrust) .hostnameVerifier(new AllowAllHostnameVerifier()) .build(); return okHttpClient; }

3、最後就看是如何進行利用Rxjava(觀察者模式)進行網路請求的資料通訊的

3-1首先是通過Retrofit實現第一步的業務介面的例項物件

FactoryInters.PostClickAppInfoParameterJsonBody server = retrofit.create(FactoryInters.PostClickAppInfoParameterJsonBody.class);

3-2然後是獲取被觀察者物件

 server.getJuheResult(request)

3-3繼續構造觀察者物件

  private class HttpResultSubscriber extends Subscriber<HttpResult>{
        private String method;
        public HttpResultSubscriber(String methodTag){
            this.method = methodTag;
        }
        @Override
        public void onCompleted() {

        }
        @Override
        public void onError(Throwable e) {
            StringBuffer sb = new StringBuffer();
            sb.append("[").append(method).append(".onError]").append(e);
            Log.e(TAG,sb.toString());
        }
        @Override
        public void onNext(HttpResult httpResult) {

            StringBuffer sb = new StringBuffer();
            sb.append("[").append(method).append(".onNext]")
                    .append(httpResult.getHead().toString());

            Log.i(TAG,sb.toString());
        }
    }

3-4然後進行訂閱行為

 server.getJuheResult(request)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);

如上程式碼中的subscribeOn、observeOn是進行的非同步處理–非同步
Scheduler scheduler引數就是執行訂閱操作,返回一個源觀察到的修改,使其訂閱發生在指定的執行緒
observeOn(AndroidSchedulers.mainThread())
句話說,observeOn() 指定的是它之後的操作所在的執行緒。

4、為業務介面getJuheResult封裝request請求

ArrayList<String> contact_ids = new ArrayList<>();
contact_ids.add("1475920950100");
HttpRequest httpRequest = new HttpRequest();
httpRequest.setPhone_num("18612185929");
httpRequest.setImei("123456789012345");
httpRequest.setGodin_id("4c59396301ab6274bd7892f0b31df36e");
httpRequest.setContact_ids(contact_ids);
[getJuheResult]requestJsonStr = 
                                                   {
                                                     "contact_ids": [
                                                       "1475920950100"
                                                     ],
                                                     "godin_id": "4c59396301ab6274bd7892f0b31df36e",
                                                     "imei": "123456789012345",
                                                     "phone_num": "18612185929"
                                                   }

最後看Log輸出即可–以下是上線專案,返回如下,說明通訊成功了!!!

[getJuheResult.onNext]Head{statuscode='000009', statusmsg='device and user not match'}

以上就是Retrofit+Rxjava 網路請求的簡單封裝

————————————–如下是程式碼區—————————————-
配置檔案許可權

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.godinsec.db" >
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

封裝Retrofit
RetrofitBase

package com.godinsec.db;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Safly on 2016/9/13.
 */

public abstract class RetrofitBase {
    private static final String BASEURL = "http://x-phone.cn/api/v1.0/";

    private static final long TIMEOUT = 5 * 1000;

    protected Retrofit retrofit;

    protected RetrofitBase(){
        retrofit = new Retrofit.Builder()
                .baseUrl(BASEURL)
                .client(client())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
    }

    private OkHttpClient client(){

        LauncherTrust launcherTrust = new LauncherTrust();

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
                .readTimeout(TIMEOUT,TimeUnit.MILLISECONDS)
                .sslSocketFactory(sslSocketFactory(launcherTrust),launcherTrust)
                .hostnameVerifier(new AllowAllHostnameVerifier())
                .build();
        return okHttpClient;
    }

    private SSLSocketFactory sslSocketFactory(LauncherTrust launcherTrust){

        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null,new TrustManager[]{launcherTrust},new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            e.printStackTrace();
        }
        return null;
    }
    static class LauncherTrust implements X509TrustManager {

        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

        }
        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

        }
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }
}

RetrofitManger

package com.godinsec.db;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParser;

import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * {"resultcode":"101","reason":"錯誤的請求KEY!","result":null,"error_code":10001}
 */

public class RetrofitManger extends RetrofitBase {

    private static final String TAG = "RetrofitManger";

    private Gson gson;

    private JsonParser jsonParser;

    private RetrofitManger() {
        super();
        gson = new GsonBuilder().setPrettyPrinting().create();
        jsonParser = new JsonParser();
    }

    private static final class Factory {
        private static final RetrofitManger instance = new RetrofitManger();
    }

    public static RetrofitManger getInstance() {
        return Factory.instance;
    }

    /**
     * {"phone_num": "18612185929", "imei": "123456789012345", "godin_id": "4c59396301ab6274bd7892f0b31df36e", "contact_ids": ["1475920950100"]}
     */
    public void postClickAppInfoParameterJsonBody(HttpRequest request) {
        if (request == null) {
            throw new NullPointerException("Argument request cannot be null.");
        }
        Log.d(TAG,"[getJuheResult]requestJsonStr = \n"+gson.toJson(jsonParser.parse(gson.toJson(request))));
        FactoryInters.PostClickAppInfoParameterJsonBody server = retrofit.create(FactoryInters.PostClickAppInfoParameterJsonBody.class);
        //觀察者
        Subscriber subscriber = new HttpResultSubscriber("getJuheResult");

        server.getJuheResult(request)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    private class HttpResultSubscriber extends Subscriber<HttpResult>{
        private String method;
        public HttpResultSubscriber(String methodTag){
            this.method = methodTag;
        }

        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {
            StringBuffer sb = new StringBuffer();
            sb.append("[").append(method).append(".onError]").append(e);
            Log.e(TAG,sb.toString());
        }

        @Override
        public void onNext(HttpResult httpResult) {

            StringBuffer sb = new StringBuffer();
            sb.append("[").append(method).append(".onNext]")
                    .append(httpResult.getHead().toString());

            Log.i(TAG,sb.toString());
        }
    }
}

Retrofit業務介面FactoryInters

package com.godinsec.db;
import java.util.Map;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import retrofit2.http.POST;
import retrofit2.http.Query;
import retrofit2.http.QueryMap;
import rx.Observable;
public interface FactoryInters {
    //http://x-phone.cn/api/v1.0/DeletePrivateContact
    interface PostClickAppInfoParameterJsonBody{
        @Headers({"Content-Type: application/json","Accept: application/json"})
        @POST("DeletePrivateContact")
        Observable<HttpResult> getJuheResult(@Body HttpRequest request);
    }
}

請求HttpRequest

package com.godinsec.db;

import java.util.ArrayList;

/**
 * 刪除聯絡人封裝的請求體
 * {"phone_num": "18612185929", "imei": "123456789012345", "godin_id": "4c59396301ab6274bd7892f0b31df36e", "contact_ids": ["1475920950100"]}
 */
public class HttpRequest {
    private String phone_num;
    private String imei;
    private String godin_id;
    private ArrayList<String> contact_ids;

    public ArrayList<String> getContact_ids() {
        return contact_ids;
    }

    public void setContact_ids(ArrayList<String> contact_ids) {
        this.contact_ids = contact_ids;
    }

    public String getPhone_num() {
        return phone_num;
    }

    public void setPhone_num(String phone_num) {
        this.phone_num = phone_num;
    }

    public String getImei() {
        return imei;
    }

    public void setImei(String imei) {
        this.imei = imei;
    }

    public String getGodin_id() {
        return godin_id;
    }

    public void setGodin_id(String godin_id) {
        this.godin_id = godin_id;
    }

    @Override
    public String toString() {
        return "HttpRequest{" +
                "phone_num='" + phone_num + '\'' +
                ", imei='" + imei + '\'' +
                ", godin_id='" + godin_id + '\'' +
                ", contact_ids=" + contact_ids +
                '}';
    }
}

HttpResult例項

package com.godinsec.db;

import java.util.ArrayList;

/**
 * 刪除正確返回的json格式
 * {"head": {
 * "statuscode": "000000",
 * "statusmsg": "success"
 * }
 * }
 */
public class HttpResult {

    @Override
    public String toString() {
        return "HttpResult{" +
                "head=" + head +
                '}';
    }

    private Head head;

    public Head getHead() {
        return head;
    }

    public void setHead(Head head) {
        this.head = head;
    }


    public static class Head {
        private String statuscode;
        private String statusmsg;

        public String getStatuscode() {
            return statuscode;
        }

        public void setStatuscode(String statuscode) {
            this.statuscode = statuscode;
        }

        public String getStatusmsg() {
            return statusmsg;
        }

        public void setStatusmsg(String statusmsg) {
            this.statusmsg = statusmsg;
        }

        @Override
        public String toString() {
            return "Head{" +
                    "statuscode='" + statuscode + '\'' +
                    ", statusmsg='" + statusmsg + '\'' +
                    '}';
        }
    }
}

最後看主介面MainActivity

package com.godinsec.db;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import java.util.ArrayList;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ArrayList<String> contact_ids = new ArrayList<>();
        contact_ids.add("1475920950100");

        HttpRequest httpRequest = new HttpRequest();
        httpRequest.setPhone_num("18612185929");
        httpRequest.setImei("123456789012345");
        httpRequest.setGodin_id("4c59396301ab6274bd7892f0b31df36e");
        httpRequest.setContact_ids(contact_ids);

        RetrofitManger.getInstance().postClickAppInfoParameterJsonBody(httpRequest);
    }
}