完全开源Android网络框架 — 基于JAVA原生的HTTP框架

时间:2023-03-10 07:15:45
完全开源Android网络框架 — 基于JAVA原生的HTTP框架

HttpNet网络请求框架基于HttpUrlConnection,采用Client + Request + Call的请求模型,支持https默认证书,数字安全证书、支持http代理!后续将会实现队列、缓存模块。

开源地址:Github上HttpNet,码云上:HttpNet

项目结构如下:

完全开源Android网络框架 — 基于JAVA原生的HTTP框架

使用方法:

compile 'com.haibin:httpnet:1.0.5'
HttpNetClient client = new HttpNetClient();//构建一个客户端

client.setProxy("192.168.1.1",80);//您也可以开启该客户端全局代理
默认支持Https认证,如果使用数字证书,在执行请求之前使用下面3种API导入证书即可
client.setSslSocketFactory(getAssets().open("12306.cer"));//证书文件输入流
client.setSslSocketFactory("filepath/12306.cer");//证书路径
client.setSslSocketFactoryAsString("cerValue");//证书文本 //注意,添加多个证书只能调用该方法一次,可以使用如下方式添加多个证书,该客户端导入证书之后将不能访问其它没有导入https的链接,可以重新创建一个HttpNetClient即可 InputStream is12306 = getAssets().open("12306.cer");
InputStream isGoogle = getAssets().open("google.cer");
client.setSslSocketFactory(is12306 , isGoogle ); Request request = new Request.Builder()
.encode("UTF-8")
.method("GET")
.timeout(13000)
.proxy("192.168.1.1",80) //支持HTTP代理
.url("https://kyfw.12306.cn/otn/")
.build();

GET请求构建:

Request request = new Request.Builder().encode("UTF-8")
.method("GET")
.timeout(13000)
.url("http://www.oschina.net")
.build();

POST请求构建:

RequestParams params = new RequestParams()
.put("userName","oscer")
.putFile("fileName","file")
.put("pwd","oschina");
Request request = new Request.Builder()
.encode("UTF-8")
.method("POST")
.params(params)
.timeout(13000)
.url("http://www.oschina.net")
.build();

POST JSON请求构建:

Request request = new Request.Builder()
.encode("UTF-8")
.method("POST")
.content(new JsonContent("json")
.timeout(13000)
.url("http://www.oschina.net")
.build();

执行请求:

client.newCall(request).execute(new CallBack() {
@Override
public void onResponse(Response response) {
String body = response.getBody();
InputStream is = response.toStream();//如果采用下载
} @Override
public void onFailure(Exception e) { }
});

此项目无任何内存泄露,高效优雅!

开源地址:Github上HttpNet,码云上:HttpNet