Code Monkey home page Code Monkey logo

okhttps's Introduction

logo

Maven Central License Troy.Zhou

文档

网址:https://ok.zhxu.cn

为什么用

  OkHttps 是近期开源的对 OkHttp3 轻量封装的框架,它独创的异步预处理器,特色的标签,灵活的上传下载进度监听与过程控制功能,在轻松解决很多问题的同时,设计上也力求纯粹与优雅。

  • 超级优雅的 API 设计,且链式调用,让你顺滑到底!
  • BaseURL、URL占位符、HTTP 同步 异步、WebSocket,让你想干啥就干啥!
  • JSON、Xml 等自动封装与解析,且支持与任意格式的数据解析框架集成,想用啥就用啥!
  • 同步拦截器、异步预处理器、回调执行器、全局监听、回调阻断 等等,让你扩展无限功能!
  • 文件上传下载(过程控制、进度监听),上传下载如此简单!
  • 单方法回调,充分利用 Lambda 表达式,让你代码超级简洁!
  • 超级轻量,但性能卓越!

如何使用

如艺术一般优雅,像 1、2、3 一样简单

// 同步 HTTP
List<User> users = OkHttps.sync("/users") 
        .get()                          // GET请求
        .getBody()                      // 响应报文体
        .toList(User.class);            // 自动反序列化 List 

// 异步 HTTP
OkHttps.async("/users/1")
        .setOnResponse(res -> {
            // 自动反序列化 Bean 
            User user = res.getBody().toBean(User.class);
        })
        .get();                         // GET请求

// WebSocket
OkHttps.webSocket("/chat") 
        .setOnMessage((WebSocket ws, Message msg) -> {
            // 从服务器接收消息
            Chat chat = msg.toBean(Chat.class);
            // 向服务器发送消息
            ws.send(chat); 
        })
        .listen();                     // 启动监听

请求三部曲

第一步、确定请求方式

  • 同步 HTTP - sync 方法
  • 异步 HTTP - async 方法
  • WebSocket - webSocket 方法

第二步、构建请求任务

  • addXxxPara - 添加请求参数
  • setOnXxxx - 设置回调函数
  • tag - 添加标签
  • ...

第三步、调用请求方法

HTTP 请求方法:

  • get() - GET 请求
  • post() - POST 请求
  • put() - PUT 请求
  • delete() - DELETE 请求
  • ...

Websocket 方法:

  • listen() - 启动监听

任意网络请求,都遵循请求三部曲!

相关项目

项目 最新版本 描述
okhttps 4.0.2 OkHttps 核心模块
okhttps-fastjson 4.0.2 与 fastjson 集成
okhttps-fastjson 4.0.2 与 fastjson2 集成
okhttps-fastjson 4.0.2 与 fastjson2-jsonb 集成
okhttps-gson 4.0.2 与 gson 集成
okhttps-jackson 4.0.2 与 jackson 集成
okhttps-jackson 4.0.2 与 jackson-xml 集成
okhttps-jackson 4.0.2 与 jackson-yaml 集成
okhttps-jackson 4.0.2 与 jackson-yaml 集成
okhttps-stomp 4.0.2 超级轻量的 Stomp 客户端
okhttps-xml 3.5.3 XML 解析扩展

超详细教程,请查看:https://ok.zhxu.cn

联系方式

  • 微信:
  • 由于近期交流群的二维码被爬,扫码入群方式已被关闭 库的使用上若有疑问,可先加微信【18556739726】(请备注 OkHttps)再入群交流

友情链接

[ Bean Searcher ] 比 MyBatis 效率快 100 倍的条件检索引擎,天生支持联表,使一行代码实现复杂列表检索成为可能!

[ SA Token ] 一个轻量级 Java 权限认证框架,让鉴权变得简单、优雅!

[ hrun4j ] 接口自动化测试解决方案 --工具选得好,下班回家早;测试用得对,半夜安心睡

[ Json Kit ] 超轻量级 JSON 门面工具,用法简单,不依赖具体实现,让业务代码与 Jackson、Gson、Fastjson 等解耦!

参与贡献

  1. Fork 本仓库
  2. 新建 Feat_xxx 分支
  3. 提交代码
  4. 新建 Pull Request

okhttps's People

Contributors

aohanhongzhi avatar click33 avatar davinci2014 avatar dependabot[bot] avatar greenorange520 avatar troyzhxu avatar yejunxiang avatar zpupup 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  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  avatar  avatar  avatar  avatar  avatar  avatar

okhttps's Issues

在接入Stomp后,如果app网络断开,App直接奔溃,加try-catch也还是奔溃

com.ejlchina.okhttps.internal.HttpException: WebSockt 连接异常: ws://192.168.101.233:10002/api/ws/websocket
at com.ejlchina.okhttps.internal.WebSocketTask$MessageListener.onFailure(WebSocketTask.java:252)
at okhttp3.internal.ws.RealWebSocket.failWebSocket(RealWebSocket.java:570)
at okhttp3.internal.ws.RealWebSocket$1.onFailure(RealWebSocket.java:216)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:180)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:776)
Caused by: java.net.ConnectException: Failed to connect to /192.168.101.233:10002

Stomp有办法销毁websocket吗

在activity界面初始化连接stomp activity destory调用的disconnect之后回到首页 断网之后还能收到setOnException里面的回调 disconnect没有销毁websocket吗

没有匹配[json]类型的转换器!

Describe the bug

Exception in thread "main" com.ejlchina.okhttps.internal.HttpException: 没有匹配[json]类型的转换器!
	at com.ejlchina.okhttps.internal.TaskExecutor.doMsgConvert(TaskExecutor.java:145)
	at com.ejlchina.okhttps.HttpTask.toRequestBody(HttpTask.java:699)
	at com.ejlchina.okhttps.HttpTask.buildRequestBody(HttpTask.java:689)
	at com.ejlchina.okhttps.HttpTask.prepareRequest(HttpTask.java:596)
	at com.ejlchina.okhttps.HttpTask.prepareCall(HttpTask.java:585)
	at com.ejlchina.okhttps.internal.AsyncHttpTask.lambda$request$0(AsyncHttpTask.java:263)
	at com.ejlchina.okhttps.internal.HttpClient.preprocess(HttpClient.java:184)
	at com.ejlchina.okhttps.internal.AsyncHttpTask.request(AsyncHttpTask.java:255)
	at com.ejlchina.okhttps.internal.AsyncHttpTask.post(AsyncHttpTask.java:217)
	at com.hellosouth.file_transfer.utils.OkHttpUtils.main(OkHttpUtils.java:231)

To Reproduce

  Map<String, Object> map = new HashMap<>();
        map.put("uploadId", "uploadId");
//        map.put("base64",base64);
        map.put("total", 10);
        map.put("current", 2);
        HTTP http = HTTP.builder().bodyType(OkHttps.JSON).build();
        http.async(UPLOAD_URL)
                .bodyType(OkHttps.JSON)
                .addBodyPara(map)
//                .setBodyPara(map)
                .setOnException((IOException e) -> {
                    // 异常回调
                    e.printStackTrace();
                })
                .setOnResponse((HttpResult res) -> {

                    // 响应回调
                    int status = res.getStatus();       // 状态码
                    Headers headers = res.getHeaders(); // 响应头
                    HttpResult.Body body = res.getBody();          // 报文体
                    System.out.println(body);

                })
                .post();
  <!-- okhttps -->
        <dependency>
            <groupId>com.ejlchina</groupId>
            <artifactId>okhttps</artifactId>
            <version>2.4.2</version>
        </dependency>

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

WebSocket 连接异常

10-25 12:36:18.967 7197-7215/? E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
Process: com.dppdkai.luckypandemo, PID: 7197
com.ejlchina.okhttps.internal.HttpException: WebSockt 连接异常: ws://127.0.0.1/aka/dserver
at com.ejlchina.okhttps.internal.WebSocketTask$MessageListener.onFailure(WebSocketTask.java:278)
at okhttp3.internal.ws.RealWebSocket.failWebSocket(RealWebSocket.java:570)
at okhttp3.internal.ws.RealWebSocket$1.onResponse(RealWebSocket.java:199)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:174)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.net.ProtocolException: Expected HTTP 101 response but was '403 Forbidden'
at okhttp3.internal.ws.RealWebSocket.checkUpgradeSuccess(RealWebSocket.java:224)
at okhttp3.internal.ws.RealWebSocket$1.onResponse(RealWebSocket.java:195)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:174) 
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
at java.lang.Thread.run(Thread.java:818) 

okhttps-gson:3.0.0版本是不是有问题,HTTP这个类就没有

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

STOMP心跳与服务器断开连接后没有任何操作和处理

com.ejlchina.okhttps.internal.WebSocketTask

	private void schedulePing() {
		if (!isConnected()) {
			return;
		}
		int delay = (int) (pingSeconds + lastPingSecs - nowSeconds());
		httpClient.executor.requireScheduler().schedule(() -> {
			if (!isConnected()) {
				return;
			}
			WebSocket ws = webSocket;
			if (nowSeconds() - lastPingSecs >= pingSeconds && ws != null) {
				ByteString ping = pingSupplier != null ? pingSupplier.getPing() : ByteString.EMPTY;
				ws.send(ping);
				lastPingSecs = nowSeconds();
			}
			schedulePing();
		}, delay, TimeUnit.SECONDS);
	}

	/**
	 * 检测服务器的心跳响应
	 */
	private void schedulePong() {
		if (!isConnected()) {
			return;
		}
		int delay = (int) (pongSeconds + lastPongSecs - nowSeconds());
		httpClient.executor.requireScheduler().schedule(() -> {
			if (!isConnected()) {
				return;
			}
			long noPongSeconds = nowSeconds() - lastPongSecs;
			if (noPongSeconds > 3L * pongSeconds) {
				WebSocketImpl ws = webSocket;
				if (ws != null) {
					Exception e = new SocketTimeoutException("Server didn't pong heart-beat on time. Last received at " + noPongSeconds + " seconds ago.");
					((RealWebSocket) ws.webSocket).failWebSocket(e, null);
				}
			} else {
				schedulePong();
			}
		}, delay, TimeUnit.SECONDS);
	}

如代码中所示,两个心跳检测中,判断与服务器连接断开!isConnected()后,直接return,此处是否应该抛出异常或触发onDisconnected回调。

OkHttps.sync

请问下 OkHttps.sync 该用法怎么配置proxy 代理地址和端口?

没有添加报文体参数时,POST 请求都会以 form 表单的形式提交

形如以下代码:

OkHttps.sync("http://xxxxx")
    .bodyType(OkHttps.JSON)
    .post();

期望发出的 Content-Typeapplication/json,但实际发出的却是 application/x-www-form-urlencoded

即:
所有应该有报文体,但没有添加 bodyPara 的请求,都会默认以空表单的形式提交。

当前的可行的避免方案有:

OkHttps.sync("http://xxxxx")
    .bodyType(OkHttps.JSON)
    .addBodyPara(null)    // 添加一个 空 报文体参数
    .post();

Crash when throw JsonSyntaxException and doesn't callback through exceptionListener or setOnException.

Describe the bug
服务器正常应返回json,但是异常情况下返回html,exceptionListener 和 setOnException不会走直接崩溃

    com.ejlchina.okhttps.internal.HttpException: 转换失败
     Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
     Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

To Reproduce
这样用的

http = HTTP.builder()
                .addMsgConvertor(new GsonMsgConvertor())
                .baseUrl(Constant.getApiBaseUrl())
                .exceptionListener((HttpTask<?> task, IOException error) -> {
                  error.printStackTrace();
                  return true;
                })
                .build();

try{
            http.async(Constant.LOGIN_SUFFIX)
                    .bodyType("json")
                    .setBodyPara(user)
                    .setOnResBean(new TypeRef<BaseResp<LoginResp>>() {}, result -> {
                        callback.onResponse(result);
                    })
                    .setOnException(ex ->{
                        callback.onFail(ex);
                    })
                    .post();
        }catch (Exception e){
            e.printStackTrace();
        }

Expected behavior
期望 json转换异常也会在onexception抛出.

Smartphone (please complete the following information):

  • Device: HongMi2s
  • OS: Android 7.1.2
  • Version OKHTTPS 3.0.0-Gson

经常会报The destination [" + destination + "] has already been subscribed!这个异常

每次都是在Stomp连接成功的回调里面开始订阅,订阅之前会执行一次取消订阅方法,但是有时候过了很久APP会奔溃报上述异常;
还有登录成功或者打开首页都会执行Stomp的连接方法导致同时可能发起多个连接请求;只通过stomp.isConnected()判断也不可靠,因为有时候真在连接中
//设置监听
stomp.setOnConnected(new OnCallback() {
@OverRide
public void on(Stomp data) {
// 服务器连接成功回调
Log.i("Stomp", "OnConnected");
//开始订阅消息
subscribe();
}
});

       //取消订阅
        stomp.unsubscribe(destination);
        //订阅
        stomp.subscribe(destination,null,(com.ejlchina.stomp.Message msg) -> {

      }

WebSocket 连接异常

E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
Process: com.dppdkai.luckypandemo, PID: 10154
com.ejlchina.okhttps.internal.HttpException: WebSockt 连接异常: ws://myphp.com
at com.ejlchina.okhttps.internal.WebSocketTask$MessageListener.onFailure(WebSocketTask.java:278)
at okhttp3.internal.ws.RealWebSocket.failWebSocket(RealWebSocket.java:570)
at okhttp3.internal.ws.RealWebSocket$1.onResponse(RealWebSocket.java:199)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:174)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:929)
Caused by: java.net.ProtocolException: Expected HTTP 101 response but was '200 OK'
at okhttp3.internal.ws.RealWebSocket.checkUpgradeSuccess(RealWebSocket.java:224)
at okhttp3.internal.ws.RealWebSocket$1.onResponse(RealWebSocket.java:195)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:174) 
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 
at java.lang.Thread.run(Thread.java:929) 

Stomp 使用的是自签的https 需要配置sslSocketFactory和hostnameVerifier

WebSocketTask webSocketTask = OkHttps.webSocket(UrlConfig.WS_STOMP);
stomp = Stomp.over(webSocketTask);
这么没有api可以获取到OkHttps中的http来设置sslSocketFactory

public static WebSocketTask webSocket(String url) {
return getHttp().webSocket(url);
}

static synchronized HTTP getHttp() {
if (http != null) {
return http;
}
HTTP.Builder builder = HTTP.builder();
ConvertProvider.inject(builder);
Config.config(builder);
http = builder.build();
return http;
}
我需要Https中的http对象
http .config(b -> {
b.sslSocketFactory(mySSLSocketFactory, myTrustManager);
b.hostnameVerifier(myHostnameVerifier);
})

使用Stomp出现粘包问题

stomp.topic("/your-topic", (Message msg)
订阅收到数据后,我的Message是多条消息,请问这个该如何解析?

WHttpTask onFailure 非能重置webSocket连接中状态

Describe the bug
STOMP 重连时, 服务器关闭状态下在次调用stomp.connect()时, WebSocket status 任然是 STATUS_CONNECTING.
主要原因在WHttpTask.onFailure中未能重置WebSocket状态

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

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.