Skip to content

基础使用

xuexiangjys edited this page Jan 31, 2021 · 4 revisions

使用XHttp默认API进行请求

1.使用XHttp.post、XHttp.get、XHttp.delete、XHttp.put、XHttp.downLoad构建请求。

2.修改request的请求参数。

方法名 类型 默认值 备注
baseUrl String 设置该请求的baseUrl
timeOut long 15000 设置超时时间
accessToken boolean false 是否需要验证token
threadType String 设置请求的线程调度类型
syncRequest boolean false 设置是否是同步请求(不开子线程)
onMainThread boolean true 请求完成后是否回到主线程
upJson String "" 上传Json格式的数据请求
keepJson boolean false 返回保持json的形式
retryCount int 设置超时重试的次数
retryDelay int 设置超时重试的延迟时间
retryIncreaseDelay int 设置超时重试叠加延时
headers HttpHeaders 添加头信息
params HttpParams 设置表单请求参数
cacheMode CacheMode CacheMode.NO_CACHE 设置缓存的模式

3.调用execute方法执行请求。execute一般有如下两种方式:

  • execute(CallBack callBack): 直接回调结果。

  • execute(Class clazz)和execute(Type type): 回调Observable对象,可通过订阅获取到结果。

4.请求使用演示

XHttp.get("/user/getAllUser")
        .syncRequest(false) //异步请求
        .onMainThread(true) //回到主线程
        .execute(new SimpleCallBack<List<User>>() {
            @Override
            public void onSuccess(List<User> response) {
                refreshLayout.finishRefresh(true);
                if (response != null && response.size() > 0) {
                    mUserAdapter.refresh(response);
                    mLlStateful.showContent();
                } else {
                    mLlStateful.showEmpty();
                }
            }
            @Override
            public void onError(ApiException e) {
                refreshLayout.finishRefresh(false);
                mLlStateful.showError(e.getMessage(), null);
            }

        });
XHttp.post("/user/deleteUser")
        .params("userId", item.getUserId())
        .execute(Boolean.class)
        .subscribeWith(new TipRequestSubscriber<Boolean>() {
            @Override
            protected void onSuccess(Boolean aBoolean) {
                ToastUtils.toast("删除成功!");
                setFragmentResult(RESULT_OK, null);
                popToBack();
            }
        });


使用XHttpRequest封装的统一请求实体进行请求

需要注意的是,目前仅支持post请求。

在使用它之前,需要下载/定义对应的实体协议,如下:

@RequestParams(url = "/user/addUser", accessToken = false)
public static class UserService_AddUser extends XHttpRequest {

    /**
     *
     */
    public User request;

    @Override
    protected Boolean getResponseEntityType() {
        return null;
    }
}

1.注解说明

  • @RequestParams
注解参数 类型 默认值 备注
baseUrl String "" 设置该请求的baseUrl
url String "" 请求网络接口地址
timeout long 15000 设置超时时间
keepJson boolean false 是否保存json
accessToken boolean true 设置是否需要验证token
cacheMode CacheMode CacheMode.NO_CACHE 设置请求的缓存模式
cacheTime long -2(使用全局设置) 设置缓存有效时间
  • @ParamKey
注解参数 类型 默认值 备注
key String / 请求参数的key

2.使用XHttpSDK进行请求。

  • post(XHttpRequest xHttpRequest, boolean isSyncRequest, boolean toMainThread): 获取PostRequest请求(使用实体参数名作为请求Key)。

  • postToMain(XHttpRequest xHttpRequest): 获取PostRequest请求(主线程->主线程)。

  • postToIO(XHttpRequest xHttpRequest): 获取PostRequest请求(主线程->子线程)。

  • postInThread(XHttpRequest xHttpRequest): 获取PostRequest请求(子线程->子线程)。

  • execute(XHttpRequest xHttpRequest, boolean isSyncRequest, boolean toMainThread) : 执行PostRequest请求,返回observable对象(使用实体参数名作为请求Key)。

  • executeToMain(XHttpRequest xHttpRequest): 执行post请求,返回observable对象(主线程->主线程)

  • executeToMain(XHttpRequest xHttpRequest,BaseSubscriber<T> subscriber): 执行post请求并进行订阅,返回订阅信息(主线程->主线程)

3.请求使用演示。

XHttpRequest req = ApiProvider.getAddUserReq(getRandomUser());
XHttpSDK.executeToMain(req, new ProgressLoadingSubscriber<Boolean>(mIProgressLoader) {
    @Override
    public void onSuccess(Boolean aBoolean) {
        ToastUtils.toast("用户添加成功!");
        mRefreshLayout.autoRefresh();
    }
});

使用XHttpProxy代理进行请求

在使用它之前,需要下载/定义对应的接口协议,如下:

/**
 * 图书管理
 */
public interface IBook {
    /**
     * 购买书
     *
     * @param bookId 图书ID
     * @param userId 用户ID
     * @param number 购买数量
     */
    @NetMethod(parameterNames = {"bookId", "userId", "number"}, url = "/order/addOrder/", accessToken = false)
    Observable<Boolean> buyBook(int bookId, int userId, int number);
    /**
     * 获取图书
     *
     * @param pageNum 第几页数
     * @param pageSize 每页的数量
     */
    @NetMethod(parameterNames = {"pageNum", "pageSize"}, paramType = FORM_BODY, url = "/book/findBooks/", accessToken = false)
    Observable<List<Book>> getBooks(int pageNum, int pageSize);

    /**
     * 获取所有图书
     *
     */
    @NetMethod(action = GET, url = "/book/getAllBook", accessToken = false)
    Observable<List<Book>> getAllBooks();
}

1.注解说明

  • @NetMethod
注解参数 类型 默认值 备注
parameterNames String[] {} 参数名集合
paramType int JSON=1 param的类型
action String POST="post" 请求动作
baseUrl String "" 设置该请求的baseUrl
url String "" 请求网络接口地址
timeout long 15000 设置超时时间
keepJson boolean false 是否保存json
accessToken boolean true 设置是否需要验证token
cacheMode CacheMode CacheMode.NO_CACHE 设置请求的缓存模式
cacheTime long -2(使用全局设置) 设置缓存有效时间
cacheKeyIndex int -1(所有参数) 作为缓存key的请求参数索引

2.使用XHttpProxy进行请求。

构建一个XHttpProxy,将定义的api接口传入后,直接调用接口进行请求。

构造XHttpProxy可以传入ThreadType,默认是ThreadType.TO_MAIN

  • TO_MAIN: executeToMain(main -> io -> main)

【注意】请确保网络请求在主线程中【实质是异步请求(切换到io线程),且响应的线程又切换至主线程】

  • TO_IO: executeToIO(main -> io -> io)

【注意】请确保网络请求在主线程中【实质是异步请求(切换到io线程),不过响应的线程不变,还是之前请求的那个io线程】

  • IN_THREAD: executeInThread(io -> io -> io)

【注意】请确保网络请求在子线程中才可以使用该类型【实质是不做任何线程调度的同步请求】

3.请求使用演示。

//使用XHttpProxy进行接口代理请求
XHttpProxy.proxy(TestApi.IOrder.class)
        .buyBook(mBookAdapter.getItem(position).getBookId(), UserManager.getInstance().getUser().getUserId(), 1)
        .subscribeWith(new TipRequestSubscriber<Boolean>() {
            @Override
            public void onSuccess(Boolean aBoolean) {
                ToastUtils.toast("图书购买" + (aBoolean ? "成功" : "失败") + "!");
                mRefreshLayout.autoRefresh();
            }
        });

文件上传和下载

文件上传

使用post的文件表单【multipart/form-data】上传。使用XHttp.post,然后使用params传递附带的参数,使用uploadFile传递需要上传的文件,使用示例如下:

mIProgressLoader.updateMessage("上传中...");
XHttp.post("/book/uploadBookPicture")
        .params("bookId", book.getBookId())
        .uploadFile("file", FileUtils.getFileByPath(mPicturePath), new IProgressResponseCallBack() {
            @Override
            public void onResponseProgress(long bytesWritten, long contentLength, boolean done) {

            }
        }).execute(Boolean.class)
        .compose(RxLifecycle.with(this).<Boolean>bindToLifecycle())
        .subscribeWith(new ProgressLoadingSubscriber<Boolean>(mIProgressLoader) {
            @Override
            public void onSuccess(Boolean aBoolean) {
                mIsEditSuccess = true;
                ToastUtils.toast("图片上传" + (aBoolean ? "成功" : "失败") + "!");
            }
        });

文件下载

使用XHttp.downLoad,传入下载的地址url、保存文件的路径以及文件名即可完成文件的下载,使用示例如下:

XHttp.downLoad(BookAdapter.getBookImgUrl(book))
        .savePath(PathUtils.getExtPicturesPath())
        .execute(new DownloadProgressCallBack<String>() {
            @Override
            public void onStart() {
                HProgressDialogUtils.showHorizontalProgressDialog(getContext(), "图片下载中...", true);
            }

            @Override
            public void onError(ApiException e) {
                ToastUtils.toast(e.getMessage());
                HProgressDialogUtils.cancel();
            }

            @Override
            public void update(long bytesRead, long contentLength, boolean done) {
                HProgressDialogUtils.onLoading(contentLength, bytesRead); //更新进度条
            }

            @Override
            public void onComplete(String path) {
                ToastUtils.toast("图片下载成功, 保存路径:" + path);
                HProgressDialogUtils.cancel();
            }
        });