HttpNet網絡請求框架基於HttpUrlConnection,采用Client + Request + Call的請求模型,支持https默認證書,數字安全證書、支持http代理!后續將會實現隊列、緩存模塊。
開源地址:Github上HttpNet,碼雲上:HttpNet
項目結構如下:
使用方法:
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) { } });
此項目無任何內存泄露,高效優雅!