Code Monkey home page Code Monkey logo

rxretrohttp's Introduction

RxRetroHttp

License

Android http request lib, supports multiple api result data structures and multiple urls

Http请求库,支持同时存在多种返回格式和多个base url(中文文档

Why RxRetroHttp

In some case, we have to include more than one http request style -- eg. multiple result structure, multiple host address, multiple http settings, etc-- in one app.

This usually happens when we need to use some third party api or combine multiple system in one project.

RxRetroHttp suppose to simplify your http request realization in this situation.

Gradle via JitPack

Add it in your root build.gradle at the end of repositories:

allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}

Add the dependency

dependencies {
    implementation 'com.github.BakerJQ:RxRetroHttp:1.2.10'
}

How to use

Initialize

Main Api Request

Initialize the sdk in Application, the code below shows the initialization of the main url request settings

RxRetroHttp.init(this)
           .setBaseUrl("https://api.github.com/")//your main url
           .setDefaultErrMsg("Github开小差了")//default error hint message
           .setApiResultClass(GithubApiResult.class)//your main api result structure, if not, will use default gson converter
           .generateRetroClient()

Other Api Request

If your app includes other api request, try the code below

Mention:

  • You need to do this after you called init()
  • DON'T forget to add the 'Tag' in generateRetroClient() function
  • If you don't set an ApiResultClass, the lib will use GsonConverterFactory as default, this means that the lib will not deal with response logic for you, or you can add your own ResponseConverter
RxRetroHttp.getInstance()
           .setApiResultClass(YourApiResult.class)//other result
           .setBaseUrl("http://host/api/data/")//other url
           .generateRetroClient("YourTag");//other request tag

Settings

You can customize your http settings by get and reset the builders, or calling setting functions

Mention: This must be done AFTER init() and BEFORE generateRetroClient() function

RxRetroHttp.init().setXXX().setXXX();
Retrofit.Builder retrofitBuilder = RxRetroHttp.getRetrofitBuilder();
retrofitBuilder.setXXX().setXXX();
OkHttpClient.Builder okHttpBuilder = RxRetroHttp.getOkHttpClientBuilder();
okHttpBuilder.setXXX().setXXX();
RxRetroHttp.getInstance().generateRetroClient();
//RxRetroHttp.getInstance().generateRetroClient("YourTag")

Api Request

Step 1. Define Api Result Structure by Implement IApiResult

Code below is just a simple sample

public class YourApiResult<T> implements IApiResult<T> {
    private int code;//result code
    private String msg;//result message
    private T result;//result data
    //define what means a successful result(eg. code == 1)
    @Override
    public boolean isSuccess();
    //return the structured data
    @Override
    public T getData();
    //return the message
    @Override
    public String getResultMsg();
    //return the code
    @Override
    public String getResultCode();
    //return the key name of "result" in the response json
    @Override
    public String getDataField();
}

Step 2. Define Retrofit Api Service

Define the ApiService, to be mentioned, you DO NOT need to use wrapped api result like "Observable<YourApiResult< TestInfo >>", and add RetroTag annotation if this is a tagged request

@RetroTag("YourTag")
public interface YourApiService {
    @GET("test/info")
    Observable<TestInfo> getTestInfo();
    @GET("test/list")
    Observable<List<TestInfo>> getTestInfo();
}

Step 3. Call Request

Just define a call like Retrofit

RxRetroHttp.create(YourApiService.class).getTestInfo()

Mock Data

You can mock your api data in two ways: from file or from json string.

You should enable mock when init;

RxRetroHttp.init(this).setMockEnable(true)

Mock From File

Step 1. Put your mock data file under assets dir

Step 2. Add headers to your api function

@Headers({RxRetroHttp.MOCK_FILE_PATH_KEY + ":mockfile.json")
@GET("test/info")
Observable<TestInfo> getTestInfo();

Mock From Json String

Just add headers to your api function

@Headers({RxRetroHttp.MOCK_DATA_KEY + ":{\"testInfo\":\"info\"}")
@GET("test/info")
Observable<TestInfo> getTestInfo();

Header Keys

key desc
MOCK_DATA_KEY mock json string
MOCK_FILE_PATH_KEY mock assets file path
MOCK_ENABLE_KEY enable or disable mock
MOCK_DELAY_KEY delay duration of response

Proguard

  • Add Retrofit proguard
  • Add OkHttp proguard
  • Deal with your data entity

For Android Api Level 21-

For 21- projects, add the dependency like below

dependencies {
    implementation ('com.github.BakerJQ:RxRetroHttp:1.2.0'){
        exclude group: 'com.squareup.okhttp3', module: 'okhttp'
    }
    implementation 'com.squareup.okhttp3:okhttp:3.12.0'
}

Thanks

Thanks To (RxEasyHttp

License

RxRetroHttp is released under the Apache 2.0 license.

Copyright 2019 BakerJ.

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 following link.

     http://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.

rxretrohttp's People

Contributors

bakerjq avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

rxretrohttp's Issues

请求错误时 ApiException的handleException方法有问题

if (!apiResult.isSuccess()) {
Log.e("----------------","getResultCode="+apiResult.getResultCode());
throw new ServerException(apiResult.getResultMsg(), apiResult.getResultCode());
}
当我请求错误时,没有弹出我的msg 而是在ApiException中的handleException方法里面走的else 为什么没有走else if (e instanceof ServerException) 需要怎么才走这个

微信登录时微信信息获取该怎么请求?

@get("userinfo")
Observable getWeChat(@query("access_token") String access_token,
@query("openid") String openid);

@GET("oauth2/access_token")
Observable<WeChatToken> getAccessToken(@Query("appid") String appid,
                                       @Query("secret") String secret,
                                       @Query("code") String code,
                                       @Query("grant_type") String grant_type);

请求失败了

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.