Rxjava 、Retrofit、Okhttp整合

来源:互联网 发布:打印机正在接收数据 编辑:程序博客网 时间:2024/06/01 21:57

Rxjava 、Retrofit、Okhttp整合

开发环境Android Studio2.2.2

 apply plugin: 'com.android.library'android {    compileSdkVersion 24    buildToolsVersion "24.0.1"    defaultConfig {        minSdkVersion 8        targetSdkVersion 24        versionCode 1        versionName "1.0"    }    buildTypes {        release {            minifyEnabled false            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'        }    }}dependencies {    compile fileTree(dir: 'libs', include: ['*.jar'])    compile 'com.android.support:appcompat-v7:24.0.0-beta1'    compile files('libs/adapter-rxjava-2.1.0.jar')    compile files('libs/rxandroid.jar')    compile files('libs/okhttp-3.1.2.jar')    compile files('libs/okio-1.6.0.jar')    compile files('libs/retrofit-2.1.0.jar')    compile files('libs/rxjava-1.1.10.jar')//    compile 'com.google.code.gson:gson:2.3.1'}

请求整合基类

public class VPNetWork {    public static final String tag = "VPNetWork";    public static final   MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");    public static final String BASE_URL ="https://httpbin.org/";    private static VpLogInterface mVpLogInterface;    private static OkHttpClient okHttpClient;    //private static CallAdapter.Factory rxJavaCallAdapterFactory = RxJavaCallAdapterFactory.create();    public static VpLogInterface getVpLogInterface() {        if (mVpLogInterface == null) {            okHttpClient = new OkHttpClient.Builder().addInterceptor(new LoggingInterceptor()).build();            Retrofit retrofit = new Retrofit.Builder().client(okHttpClient)                    .baseUrl(BASE_URL)                    .addConverterFactory(StringConverterFactory.create())                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())                    .build();            mVpLogInterface = retrofit.create(VpLogInterface.class);        }        NetLog.d(tag,"getVpLogInterface");        return mVpLogInterface;    }    static class  LoggingInterceptor implements Interceptor {          @Override public Response intercept(Interceptor.Chain chain) throws IOException {            Request request = chain.request();            long t1 = System.nanoTime();            NetLog.d("log",String.format("Sending request %s on %s%n%s",                request.url(), chain.connection(), request.headers()));            RequestBody rbBody = request.body();            //rbBody.            Response response = chain.proceed(request);            long t2 = System.nanoTime();            NetLog.d("log",String.format("Received response for %s in %.1fms%n%s",                response.request().url(), (t2 - t1) / 1e6d, response.headers()));            return response;          }        }    /**     * 请求参数     * @param params     * @return     */    public static RequestBody createRequestBody(VpRequestParams params){        NetLog.d("request", "params : " + params);        if (TextUtils.isEmpty(params.jsonParams)) { // Form表单            okhttp3.FormBody.Builder builder = new FormBody.Builder();            // add 参数            for (ConcurrentHashMap.Entry<String, String> entry : params.urlParams.entrySet()) {// 增加url params                builder.add(entry.getKey(), entry.getValue());            }            return builder.build();        }else { // body text            return RequestBody.create(JSON_TYPE, params.jsonParams);        }    }    /**     * 文件上传     * @param params     * @return     */    public static MultipartBody createFileRequestBody(VpRequestParams params){        NetLog.d("request", "params:" + params);        Builder builder = new MultipartBody.Builder();        //add 参数         for (ConcurrentHashMap.Entry<String, String> entry : params.urlParams.entrySet()) {//增加url params             builder.addFormDataPart(entry.getKey(), entry.getValue());         }         for (ConcurrentHashMap.Entry<String, VpRequestParams.FileWrapper> entry : params.fileParams.entrySet()) {//增加url file             builder.addFormDataPart(entry.getKey(), entry.getValue().customFileName,                        RequestBody.create(MediaType.parse(entry.getValue().contentType), entry.getValue().file));         }        builder.setType(MultipartBody.FORM);        MultipartBody requestBody = builder.build();        return requestBody;    }    public static Observable<String> request(final Observable<String> observable) {        final HashMap<String, String> params = new HashMap<String, String>();        params.put("name", "tanping");        params.put("pass", "123456");//      return VPNetWork.getVpLogInterface().getT("login", params)//              .subscribeOn(Schedulers.io())//              .flatMap(new Func1<String, Observable<String>>() {////                  @Override//                  public Observable<String> call(String paramT) {////                        if (true) {////                            int a = 1/0;////                        }//                      return observable;//                  }//              });        return null;    }}

结果返回转化类,将ResponseBody 中的字节流转换为 String

/** * Created by tp */public class StringConverterFactory extends Converter.Factory {    public static StringConverterFactory create() {        return new StringConverterFactory();    }    private StringConverterFactory() {    }    @Override    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,                                                            Retrofit retrofit) {        return new StringResponseBodyConverter();    }    @Override    public Converter<?, RequestBody> requestBodyConverter(Type type,                                                          Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {        return new StringRequestBodyConverter();    }    /**     * Created by       */    public static class StringRequestBodyConverter  implements Converter<String, RequestBody> {        private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");        private static final Charset UTF_8 = Charset.forName("UTF-8");        StringRequestBodyConverter() {        }        @Override public RequestBody convert(String value) throws IOException {            NetLog.d("netrequest", ""+value);            Buffer buffer = new Buffer();            Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);            writer.write(value);            writer.close();            return RequestBody.create(MEDIA_TYPE, buffer.readByteString());        }    }    /**     * Created by       */    public static class StringResponseBodyConverter implements Converter<ResponseBody, String> {        @Override        public String convert(ResponseBody value) throws IOException {            try {                return value.string();            } finally {                value.close();            }        }}}
public interface VpLogInterface {////   @GET("get")//   Observable<String> getT(@Query("q") String query, @QueryMap HashMap<String, String> params);////   @POST("post")//   Observable<String> postT(@QueryMap HashMap<String, String> params);//////   @POST("post")//   Observable<String> postFrom(@Query("token") String token,@Body RequestBody params);////////   @POST("post")//   Observable<String> uploadFile(@Body MultipartBody params);    @POST("post")    Observable<String>  write(@Body RequestBody params);}

各种参数组合类,分装了file map等请求包装

/*    Android Asynchronous Http Client    Copyright (c) 2011 James Smith <james@loopj.com>    https://loopj.com    Licensed under the Apache License, Version 2.0 (the "License");    you may not use this file except in compliance with the License.    You may obtain a copy of the License at        https://www.apache.org/licenses/LICENSE-2.0    Unless required by applicable law or agreed to in writing, software    distributed under the License is distributed on an "AS IS" BASIS,    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.    See the License for the specific language governing permissions and    limitations under the License.*/package com.vp.log;import android.text.TextUtils;import java.io.File;import java.io.FileNotFoundException;import java.io.Serializable;import java.util.HashMap;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;/** * @author tp * A collection of string request parameters or files to send along with requests made from an * <pre> * RequestParams params = new RequestParams(); * params.put("username", "james"); * params.put("password", "123456"); * params.put("email", "my&#064;email.com"); * params.put("profile_picture", new File("pic.jpg")); // Upload a File * params.put("profile_picture2", someInputStream); // Upload an InputStream * params.put("profile_picture3", new ByteArrayInputStream(someBytes)); // Upload some bytes * * Map&lt;String, String&gt; map = new HashMap&lt;String, String&gt;(); * map.put("first_name", "James"); * map.put("last_name", "Smith"); * params.put("user", map); // url params: "user[first_name]=James&amp;user[last_name]=Smith" * * Set&lt;String&gt; set = new HashSet&lt;String&gt;(); // unordered collection * set.add("music"); * set.add("art"); * params.put("like", set); // url params: "like=music&amp;like=art" * * List&lt;String&gt; list = new ArrayList&lt;String&gt;(); // Ordered collection * list.add("Java"); * list.add("C"); * params.put("languages", list); // url params: "languages[0]=Java&amp;languages[1]=C" * </pre> */public class VpRequestParams implements Serializable {    protected final static String LOG_TAG = "RequestParams";    protected final ConcurrentHashMap<String, String> urlParams = new ConcurrentHashMap<String, String>();    protected final ConcurrentHashMap<String, FileWrapper> fileParams = new ConcurrentHashMap<String, FileWrapper>();    protected final ConcurrentHashMap<String, String> heads = new ConcurrentHashMap<String, String>();    protected String jsonParams ;    protected boolean isRepeatable = true; //是否 重复尝试    protected String contentEncoding = "utf-8";    protected boolean isShowDialog =false ;//是否显示对话框    /**     * Constructs a new empty {@code RequestParams} instance.     */    public VpRequestParams() {        this((Map<String, String>) null);    }    /**     * Constructs a new RequestParams instance containing the key/value string params from the     * specified map.     *     * @param source the source key/value string map to add.     */    public VpRequestParams(Map<String, String> source) {        if (source != null) {            for (Map.Entry<String, String> entry : source.entrySet()) {                put(entry.getKey(), entry.getValue());            }        }    }    /**     * Constructs a new RequestParams instance and populate it with a single initial key/value     * string param.     *     * @param key   the key name for the intial param.     * @param value the value string for the initial param.     */    public VpRequestParams(final String key, final String value) {        this(new HashMap<String, String>() {{            put(key, value);        }});    }    /**     * Constructs a new RequestParams instance and populate it with multiple initial key/value     * string param.     *     * @param keysAndValues a sequence of keys and values. Objects are automatically converted to     *                      Strings (including the value {@code null}).     * @throws IllegalArgumentException if the number of arguments isn't even.     */    public VpRequestParams(Object... keysAndValues) {        int len = keysAndValues.length;        if (len % 2 != 0)            throw new IllegalArgumentException("Supplied arguments must be even");        for (int i = 0; i < len; i += 2) {            String key = String.valueOf(keysAndValues[i]);            String val = String.valueOf(keysAndValues[i + 1]);            put(key, val);        }    }    /**     * Adds a key/value string pair to the request.     *     * @param key   the key name for the new param.     * @param value the value string for the new param.     */    public void put(String key, String value) {        if (key != null && value != null) {            urlParams.put(key, value);        }    }    /**     * Adds a key/value string pair to the request.     *     * @param key   the key name for the new param.     * @param value the value string for the new param.     */    public void putHead(String key, String value) {        if (key != null && value != null) {            heads.put(key, value);        }    }    public void putJsonParams(String params){        jsonParams = params;    }    /**     * Adds a file to the request.     *     * @param key  the key name for the new param.     * @param file the file to add.     * @throws FileNotFoundException throws if wrong File argument was passed     */    public void put(String key, File file) throws FileNotFoundException {        put(key, file, null, null);    }    /**     * Adds a file to the request with custom provided file name     *     * @param key            the key name for the new param.     * @param file           the file to add.     * @param customFileName file name to use instead of real file name     * @throws FileNotFoundException throws if wrong File argument was passed     */    public void put(String key, String customFileName, File file) throws FileNotFoundException {        put(key, file, null, customFileName);    }    /**     * Adds a file to the request with custom provided file content-type     *     * @param key         the key name for the new param.     * @param file        the file to add.     * @param contentType the content type of the file, eg. application/json     * @throws FileNotFoundException throws if wrong File argument was passed     */    public void put(String key, File file, String contentType) throws FileNotFoundException {        put(key, file, contentType, null);    }    /**     * Adds a file to the request with both custom provided file content-type and file name     *     * @param key            the key name for the new param.     * @param file           the file to add.     * @param contentType    the content type of the file, eg. application/json     * @param customFileName file name to use instead of real file name     * @throws FileNotFoundException throws if wrong File argument was passed     */    public void put(String key, File file, String contentType, String customFileName) throws FileNotFoundException {        if (file == null || !file.exists()) {            throw new FileNotFoundException();        }        if (key != null) {            fileParams.put(key, new FileWrapper(file, contentType, customFileName));        }    }    /**     * Adds a int value to the request.     *     * @param key   the key name for the new param.     * @param value the value int for the new param.     */    public void put(String key, int value) {        if (key != null) {            urlParams.put(key, String.valueOf(value));        }    }    public void clearUrlParams(){        urlParams.clear();    }    /**     * Adds a long value to the request.     *     * @param key   the key name for the new param.     * @param value the value long for the new param.     */    public void put(String key, long value) {        if (key != null) {            urlParams.put(key, String.valueOf(value));        }    }    /**     * Removes a parameter from the request.     *     * @param key the key name for the parameter to remove.     */    public void remove(String key) {        urlParams.remove(key);        fileParams.remove(key);    }    /**     * Check if a parameter is defined.     *     * @param key the key name for the parameter to check existence.     * @return Boolean     */    public boolean has(String key) {        return urlParams.get(key) != null ||                fileParams.get(key) != null ;    }    public String getContentEncoding() {        return contentEncoding;    }    public void setContentEncoding(String contentEncoding) {        this.contentEncoding = contentEncoding;    }    public ConcurrentHashMap<String, String> getUrlParams() {        return urlParams;    }    public ConcurrentHashMap<String, FileWrapper> getFileParams() {        return fileParams;    }    public ConcurrentHashMap<String, String> getHeads() {        return heads;    }    public String getJsonParams() {        return jsonParams;    }    public void setJsonParams(String jsonParams) {        this.jsonParams = jsonParams;    }    public boolean isRepeatable() {        return isRepeatable;    }    public void setRepeatable(boolean isRepeatable) {        this.isRepeatable = isRepeatable;    }    public boolean isShowDialog() {        return isShowDialog;    }    public void setShowDialog(boolean isShowDialog) {        this.isShowDialog = isShowDialog;    }    @Override    public String toString() {        StringBuilder result = new StringBuilder();        for (ConcurrentHashMap.Entry<String, String> entry : urlParams.entrySet()) {            if (result.length() > 0)                result.append("&");            result.append(entry.getKey());            result.append("=");            result.append(entry.getValue());        }        for (ConcurrentHashMap.Entry<String, FileWrapper> entry : fileParams.entrySet()) {            if (result.length() > 0)                result.append("&");            result.append(entry.getKey());            result.append("=");            result.append("FILE");        }        return result.toString();    }    public void setIsRepeatable(boolean flag) {        this.isRepeatable = flag;    }    public static class FileWrapper implements Serializable {        public final File file;        public  String contentType;        public  String customFileName;        public FileWrapper(File file, String contentType, String customFileName) {            this.file = file;            this.contentType = contentType;            this.customFileName = customFileName;            if (TextUtils.isEmpty(contentType)) {                this.contentType = "image/*";            }            if (TextUtils.isEmpty(customFileName)) {                this.customFileName = file.getName();            }        }    }}

Git源码地址

https://github.com/httpping/retrofitokhttprxjava

0 0