├── .DS_Store ├── LICENSE ├── README.md ├── code-style.md ├── compatibility └── README.md ├── eventbus └── README.md ├── imageloader └── README.md ├── inject └── README.md ├── network ├── .DS_Store └── SimpleNet │ ├── .DS_Store │ ├── .classpath │ ├── .gitignore │ ├── .project │ ├── .settings │ └── org.eclipse.jdt.core.prefs │ ├── AndroidManifest.xml │ ├── LICENSE │ ├── README.md │ ├── SimpleNet_Demo │ ├── .classpath │ ├── .project │ ├── .settings │ │ └── org.eclipse.jdt.core.prefs │ ├── AndroidManifest.xml │ ├── ic_launcher-web.png │ ├── proguard-project.txt │ ├── project.properties │ ├── res │ │ ├── drawable-hdpi │ │ │ └── ic_launcher.png │ │ ├── drawable-mdpi │ │ │ └── ic_launcher.png │ │ ├── drawable-xhdpi │ │ │ └── ic_launcher.png │ │ ├── drawable-xxhdpi │ │ │ └── ic_launcher.png │ │ ├── layout │ │ │ └── activity_main.xml │ │ └── values │ │ │ ├── strings.xml │ │ │ └── styles.xml │ └── src │ │ └── com │ │ └── example │ │ └── simplenet_demo │ │ └── MainActivity.java │ ├── SimpleNet_Detail_1.md │ ├── SimpleNet_Detail_2.md │ ├── SimpleNet_Detail_3.md │ ├── images │ ├── .DS_Store │ ├── package-2.png │ ├── package.jpeg │ ├── simple_net_flow.jpg │ └── uml.jpg │ ├── libs │ └── android-support-v4.jar │ ├── proguard-project.txt │ ├── project.properties │ ├── res │ ├── drawable-hdpi │ │ └── ic_launcher.png │ ├── drawable-mdpi │ │ └── ic_launcher.png │ ├── drawable-xhdpi │ │ └── ic_launcher.png │ └── values │ │ └── strings.xml │ ├── simple_net_framework_test │ ├── .classpath │ ├── .project │ ├── .settings │ │ └── org.eclipse.jdt.core.prefs │ ├── AndroidManifest.xml │ ├── proguard-project.txt │ ├── project.properties │ ├── res │ │ ├── drawable-hdpi │ │ │ └── ic_launcher.png │ │ ├── drawable-ldpi │ │ │ └── ic_launcher.png │ │ ├── drawable-mdpi │ │ │ └── ic_launcher.png │ │ ├── drawable-xhdpi │ │ │ └── ic_launcher.png │ │ └── values │ │ │ └── strings.xml │ └── src │ │ └── com │ │ └── umeng │ │ └── network │ │ └── test │ │ ├── LURCacheTest.java │ │ └── RequestQueueTest.java │ └── src │ └── org │ └── simple │ └── net │ ├── base │ ├── Request.java │ └── Response.java │ ├── cache │ ├── Cache.java │ └── LruMemCache.java │ ├── config │ ├── HttpClientConfig.java │ ├── HttpConfig.java │ └── HttpUrlConnConfig.java │ ├── core │ ├── NetworkExecutor.java │ ├── RequestQueue.java │ ├── ResponseDelivery.java │ └── SimpleNet.java │ ├── entity │ └── MultipartEntity.java │ ├── httpstacks │ ├── HttpClientStack.java │ ├── HttpStack.java │ ├── HttpStackFactory.java │ └── HttpUrlConnStack.java │ └── requests │ ├── JsonRequest.java │ ├── MultipartRequest.java │ └── StringRequest.java ├── orm └── README.md ├── others └── README.md ├── template.md └── view └── README.md /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simple-android-framework-exchange/simple-android-opensource-framework/bd1ab9e6833a89387cad20596e41156487ffc3c9/.DS_Store -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 simple-android-framework 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Android著名开源库的简版实现 2 | 3 | ## 简述 4 | 该项目通过分析并实现Android平台知名开源框架的简单版本来提升自我,并达到深入理解各大开源库的核心原理的目的。稳定、强大的开源库一般都较为复杂,比如Universal-ImageLoader,因此简版开源库不需要完全按照原版来实现,只需要把核心架构、原理实现,并且做到可运用到实际项目中即可。在实现开源库简版的同时,作者需要写一系列文章来剖析它的实现原理以及为什么要这么设计,在提升自我的同时将框架的设计与实现、领悟分享给他人,希望大家在提升自我的同时对行业做出一些贡献。 5 | 6 | Android平台有很多优秀的开源库,如果你对这些还不是很了解,可以参考Trinea的[android-open-project](https://github.com/Trinea/android-open-project)列举的知名开源库。对一些知名开源库的分析请参考Trinea的[android-open-project-analysis](https://github.com/android-cn/android-open-project-analysis)。 7 | 8 | 我想在你了解了一些开源库,并且学习了Trinea的对开源库分析的文章之后对于开源库的核心技术就有了一定的了解。此时你可以利用这些基础来重复造这些轮子,这些轮子不必很完善、稳定,只需要展示它的核心原理、设计,并且可用即可。这样从实战中学习这些开源库,不仅能够提升技术,也能够学习这些开源库的优秀设计。 9 | 10 | 如果你对面向对象不是很了解,那么在开始之前先学习一下[面向对象的六大原则](https://github.com/simple-android-framework-exchange/android_design_patterns_analysis/blob/master/oop-principles/oop-principles.md)是非常有必要的。 11 | 12 | 13 | **QQ交流群: 413864859,希望大家踊跃参与进来。** 14 | 15 | 16 | 17 | ## 库的所属种类 18 | | 开源库类型 | 文件夹 | 19 | | ------------- |:-------------:| 20 | | 网络请求 | [network](network) | 21 | | 数据库 | [orm](orm) | 22 | | 图片加载 | [imageloader](imageloader) | 23 | | view | [view](view) | 24 | | 注入框架 | [inject](inject) | 25 | | 兼容库 | [compatibility](compatibility) | 26 | | 事件总线 | [eventbus](eventbus) | 27 | | 其他 | [others](others) | 28 | 29 | 30 | 31 | ## 开发规范简述 32 | [code-style.md](code-style.md) 33 | 34 | 35 | ## 如何参与 36 | 1. 通过git将本库clone到本地; 37 | 2. 首先将自己要实现的库、完成时间(包括设计与实现的第一篇概括性文章的完成)等填写到[任务表](#schedule)中; 38 | 3. 在对应分类下创建库的目录,例如SimpleVolley,写代码实现开源库的简版,这个简版库需要可用; 39 | 4. 创建一个demo到该库的目录下,例如你要完成的库是SimpleVolley,那么你的demo的路径则为SimpleVolley/demo; 40 | 5. 将文章的图片统一放到库名/images目录下,例如SimpleVolley/images; 41 | 6. 按照[template.md](template.md)完成库的基本介绍,并且在后续的文章中对库进行详细分析。如果没有后续文章那么建议在该介绍文件中对库的核心实现、设计进行详细分析。 42 | 7. 完成之后提交,并且push到该仓库当中。 43 | 44 | **注意,在开发过程中不要修改不属于自己的文件,避免在协作时产生冲突。** 45 | 46 | 47 | 48 | ## 任务表 49 | ### 一期任务 50 | | 原开源库名称 | 简版开源库名称 | 作者 | 分类 | 预计完成时间 | 进行状态 | 51 | | ------------- | ------------- |:-------------:| ------------- | ------------- | ------------- | 52 | | [Volley](https://github.com/mcxiaoke/android-volley) | [SimpleNet](network/SimpleNet) | [Mr.Simple](https://github.com/bboyfeiyu) | 网络请求 | 2015.3.5 | 文档未完成 | 53 | | [ImageLoader](https://github.com/nostra13/Android-Universal-Image-Loader) | [SimpleImageLoader](https://github.com/bboyfeiyu/simple_imageloader) | [Mr.Simple](https://github.com/bboyfeiyu) | 图片加载 | 2015.3.15 | 代码完成 | 54 | | [AndroidEventBus](https://github.com/bboyfeiyu/AndroidEventBus) | [AndroidEventBus](https://github.com/bboyfeiyu/AndroidEventBus) | [Mr.Simple](https://github.com/bboyfeiyu) | 其他 | 2015.3.25 | 代码完成 | 55 | | [okhttp](https://github.com/square/okhttp) | 这里填写简版库的链接 | [CodeLife](https://github.com/xiaojianchen) | 网络请求 | 2015.4.10 | | 56 | | [Retrofit](https://github.com/square/retrofit) | [SimpleRetrofit]() | [tiny-times](https://github.com/tiny-times) | 网络请求 | 2015.4.10 | | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /code-style.md: -------------------------------------------------------------------------------- 1 | # 编码规范 2 | 3 | 为了保持大家的代码一致性,进行一些代码格式的规范。 4 | 5 | * 代码缩进使用4个空格,不是Tab键。 6 | * 统一使用UTF-8编码,避免乱码问题。 7 | * 类的命名规范: 如果是Android SDK提供的Android应用组成部分,那么类名应该是类的作用的英文全称或者缩写+ Android SDK基类的名字。 8 | 9 | 例子: 10 | Activity类名字应该是 类似 MainActivity, NaviActivity (Navigation, 导航缩写Navi), TextActivity, BookActivity 11 | 12 | Service类名字缩写应该是类似 DownloadService, 13 | 每个类完成后应该有作者姓名和联系方式的注释,对自己的代码负责。如 14 | 15 | ``` 16 | /** 17 | * 类的介绍 18 | */ 19 | public class DataBack { 20 | // ... 21 | } 22 | ``` 23 | 24 | * 变量命名 25 | 变量的命名均要能够代表它的意义,即命名的字解释性。看如下示例: 26 | 27 | public变量的以小写字母开头,例如: 28 | ``` 29 | public String userName ; 30 | ``` 31 | 其他访问权限的变量的格式为 : m+能够代表变量意义的字母, 例如 : 32 | ``` 33 | private String mUserName ; 34 | ``` 35 | 36 | * 函数命名 37 | 函数的命名均要能够代表它的意义,即命名的字解释性。例如 : 38 | 39 | ``` 40 | public void saveUserInfoToDB(User user) { 41 | // code 42 | } 43 | ``` 44 | 上面的函数一看基本上知道是保存用户信息到数据库中,即命名的字解释性。 45 | 46 | * 大括号的排列 47 | 在java中两个大括号的正确格式如下 : 48 | 49 | ``` 50 | if ( condition ) { 51 | // code 52 | } else if ( condition ) { 53 | // 54 | } 55 | 56 | ``` 57 | 即两个括号并不对齐排列。 58 | 59 | * 空格问题 60 | 在条件判断、操作数、操作符之间都要添加空格,使得语句更为清晰。例如 : 61 | 62 | ``` 63 | int result = 10 + 23 - 100 / 4 ; 64 | 65 | ``` 66 | 错误的形式为 : 67 | 68 | ``` 69 | int result=10+23-100/4 ; 70 | 71 | ``` 72 | 73 | * 空行问题 74 | 在函数之间需要添加一个空行,例如: 75 | 76 | ``` 77 | 78 | private void setUserName(String aName) { 79 | // 80 | } 81 | 82 | private void setUserAge(int aAge) { 83 | // 84 | } 85 | ``` 86 | 87 | * 注释 88 | 在类、函数、变量前面尽量加上相关的注释,当然如果你觉得你的命名具有足够的自解释性那可以免掉一些注释。但是建议在类的开头、重要的函数之前写一些介绍性、原理性注释。 -------------------------------------------------------------------------------- /compatibility/README.md: -------------------------------------------------------------------------------- 1 | # 任务表 2 | | 简版框架名称 | 作者 | 预计完成时间 | 3 | | ------------- |:-------------:| ------------- | 4 | | 这里指向你的框架文件夹 | [用户名](git地址) | 完成时间 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /eventbus/README.md: -------------------------------------------------------------------------------- 1 | # 任务表 2 | | 简版框架名称 | 作者 | 预计完成时间 | 3 | | ------------- |:-------------:| ------------- | 4 | | 这里指向你的框架文件夹 | [用户名](git地址) | 完成时间 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /imageloader/README.md: -------------------------------------------------------------------------------- 1 | # 任务表 2 | | 简版框架名称 | 作者 | 预计完成时间 | 3 | | ------------- |:-------------:| ------------- | 4 | | 这里指向你的框架文件夹 | [用户名](git地址) | 完成时间 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /inject/README.md: -------------------------------------------------------------------------------- 1 | # 任务表 2 | | 简版框架名称 | 作者 | 预计完成时间 | 3 | | ------------- |:-------------:| ------------- | 4 | | 这里指向你的框架文件夹 | [用户名](git地址) | 完成时间 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /network/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simple-android-framework-exchange/simple-android-opensource-framework/bd1ab9e6833a89387cad20596e41156487ffc3c9/network/.DS_Store -------------------------------------------------------------------------------- /network/SimpleNet/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simple-android-framework-exchange/simple-android-opensource-framework/bd1ab9e6833a89387cad20596e41156487ffc3c9/network/SimpleNet/.DS_Store -------------------------------------------------------------------------------- /network/SimpleNet/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /network/SimpleNet/.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files 2 | *.apk 3 | *.ap_ 4 | 5 | # Files for the Dalvik VM 6 | *.dex 7 | 8 | # Java class files 9 | *.class 10 | 11 | # Generated files 12 | bin/ 13 | gen/ 14 | 15 | # Gradle files 16 | .gradle/ 17 | build/ 18 | 19 | # Local configuration file (sdk path, etc) 20 | local.properties 21 | 22 | # Proguard folder generated by Eclipse 23 | proguard/ 24 | 25 | # Log Files 26 | *.log 27 | -------------------------------------------------------------------------------- /network/SimpleNet/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | simple_net_framework 4 | 5 | 6 | 7 | 8 | 9 | com.android.ide.eclipse.adt.ResourceManagerBuilder 10 | 11 | 12 | 13 | 14 | com.android.ide.eclipse.adt.PreCompilerBuilder 15 | 16 | 17 | 18 | 19 | org.eclipse.jdt.core.javabuilder 20 | 21 | 22 | 23 | 24 | com.android.ide.eclipse.adt.ApkBuilder 25 | 26 | 27 | 28 | 29 | 30 | com.android.ide.eclipse.adt.AndroidNature 31 | org.eclipse.jdt.core.javanature 32 | 33 | 34 | -------------------------------------------------------------------------------- /network/SimpleNet/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate 4 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 5 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 6 | org.eclipse.jdt.core.compiler.compliance=1.6 7 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 8 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 9 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 10 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 11 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 12 | org.eclipse.jdt.core.compiler.source=1.6 13 | -------------------------------------------------------------------------------- /network/SimpleNet/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 9 | 10 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /network/SimpleNet/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Mr.Simple 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /network/SimpleNet/README.md: -------------------------------------------------------------------------------- 1 | SimpleNet 的设计与实现 2 | ==================================== 3 | > 本文为 [Android著名开源库的简版实现](https://github.com/simple-android-framework-exchange/simple-android-opensource-framework) 中的 SimpleNet 的设计与实现 4 | > 原始开源库: [Volley](https://github.com/mcxiaoke/android-volley) 5 | > 作者:[Mr.Simple](https://github.com/bboyfeiyu),开发状态:完成/未完成,校对者:[Mr.Simple](https://github.com/bboyfeiyu),校对状态:未开始 6 | 7 | 8 | ## 1. 功能介绍 9 | SimpleNet是按照Volley的基本架构和核心原理来实现,其中省略掉了一些模块,比如CacheDispathcer等。SimpleNet能够执行网络请求,默认支持的请求类型有StringRequest、JsonRequest、MultipartRequest(可传递文件、图片参数),也可以参考上述几个类自定义请求。SimpleNet执行网络请求,并且将结果投递给UI线程。其他的一些核心概念跟Volley都非常的类型,我们在这里只是以重复造轮子的态度去学习轮子构建过程,从而达到能够造轮子的地步。 10 | 11 | ## 2. 总体设计 12 | ![arch](http://img.blog.csdn.net/20150115142804901?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvYmJveWZlaXl1/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center) 13 | 14 | SimpleNet框架的基本结构类似于Volley,包括一些命名上也有跟Volley一致。它主要分为四个部分,最上面的部分为Request,即各种请求类型。例如返回的数据类型为json的对应为JsonRequest,返回数据字符串的为StringRequest,如果需要上传文件,那么你需要使用MultipartRequest,该请求只支持小文件的上传,如果上传的文件过大则会产生OOM。 15 | 16 | 第二部分为消息队列,消息队列维护了提交给网络框架的请求列表,并且根据相应的规则进行排序。默认情况下更具优先级和进入队列的顺序来执行,该队列使用的是线程安全的PriorityBlockingQueue,因为我们的队列会被并发的访问,因此需要保证访问的原子性。 17 | 18 | 第三部分是Executor,也就是网络的执行者。该Executor继承自Thread,在run方法中循环访问第二部分的请求队列,请求完成之后将结果投递给UI线程。为了更好的控制请求队列,例如请求排序、取消等操作,这里我们并没有使用线程池来操作,而是自行管理队列和Thread的形式,这样整个结构也变得更为灵活。 19 | 20 | 第四部分则是Response投递类,在第三部分的Executor中执行网络请求,Executor是Thread,但是我们并不能在主线程中更新UI,因此我们使用ResponseDelivery来封装Response的投递,保证Response执行在UI线程。 21 | 22 | 每个部分职责都相对单一,这样便于日后的升级和维护。 23 | 24 | 25 | ## 3. 流程图 26 | ![flow](images/simple_net_flow.jpg) 27 | 28 | 29 | ## 4. 详细设计 30 | ### 4.1 核心类详细介绍 31 | 32 | * SimpleNet : 网络请求队列创建工厂类; 33 | * NetworkExecutor : 执行网络请求的子线程类,不断地从请求队列中读取请求,并且执行网络请求或者从缓存中获取结果,并且将结果回调给UI线程; 34 | * RequestQueue : 网络请求队列; 35 | * ResponseDelivery : 请求结果分发器,将结果投递给UI线程; 36 | * HttpStack : 执行网络请求的接口; 37 | * HttpClientStack : 使用HttpClient执行网络请求的HttpStack子类 ( api 9以下 ); 38 | * HttpUrlConnStack : 使用HttpURLConnection执行网络请求的HttpStack子类 ( api 9及其以上 ); 39 | * Request : 网络请求基类,是一个抽象的泛型类; 40 | * Response : 请求结果类,封装了请求结果的各类信息以及结果实体的字节码数据; 41 | * JsonRequest : 返回的数据类型是JsonObject的请求; 42 | * StringRequest : 返回的数据类型是字符串的请求; 43 | * MultipartRequest : 可传递文件、图片等参数的请求,返回的类型为String; 44 | * HttpConfig : http请求配置的抽象类; 45 | 46 | SimpleNet将各个子模块分布在不同的包中,并且尽量降低与其他类型的耦合,使得整个结构清晰、简单。 47 | 48 | SimpleNet,Request是一个抽象的泛型类,泛型类型就是返回的Response类型,例如StringRequest就是继承自Request。第二部分的RequestQueue依赖于Request,Request是抽象的,因此任何Request的子类都可以传递到请求队列中来,它依赖的是抽象Request,而不是具体的某个实现,因此保证了可扩展性。你可以自己实现自己所需的Request,例如大文件的上传Request。同理,第三部分的NetworkExecutor也只是依赖于Request抽象,但这里又引入了一个类型HttpStack,这个网络请求的真正执行者,有HttpClientStack和HttpUrlConnStack,两者分别为Apache的HttpClient和java的HttpURLConnection,关于这两者的区别请参考:Android访问网络,使用HttpURLConnection还是HttpClient?。HttpStack也是一个抽象,具体使用HttpClient还是HttpURLConnection则由运行系统版本来定,HttpStackFactory会根据系统版本给框架返回对应的HttpStack。最后的ResponseDelivery比较简单了,只是通过Handler将结果投递给UI线程执行,也就是执行RequestListener的onComplete方法,此时网络执行完成,用户即可在该方法中更新UI或者相关的其他的操作。 49 | 下面我们再看看SimpleNet的工程结构,如图所示。 50 | 51 | | ![package](images/package.jpeg) | ![package](images/package-2.png) | 52 | |--------|------| 53 | ||| 54 | 55 | 这就是SimpleNet框架的基本结构了,如果期待下一篇博客的更新,就请顶个帖吧!谢谢~ 56 | 57 | ### 4.2 类关系图 58 | ![uml](images/uml.jpg) 59 | 60 | 61 | ##5. 杂谈 62 | 该项目模仿Volley简单实现了一个网络请求框架,该库没有经过严格的测试,适合用于学习,不建议运用到项目中。当然你要是觉得没有什么问题,也可以在你的项目中使用。 63 | 本篇文章,我们对SimpleNet做了一个简介,在后续的文章中我们再进行详细介绍,敬请期待。[SimpleNet的Request、Response类与请求队列](SimpleNet_Detail_1.md)、[SimleNet的Http请求分发与执行](SimpleNet_Detail_2.md)、[SimpleNet的请求配置与Response缓存](SimpleNet_Detail_3.md)。 64 | 65 | -------------------------------------------------------------------------------- /network/SimpleNet/SimpleNet_Demo/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /network/SimpleNet/SimpleNet_Demo/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | SimpleNet_Demo 4 | 5 | 6 | 7 | 8 | 9 | com.android.ide.eclipse.adt.ResourceManagerBuilder 10 | 11 | 12 | 13 | 14 | com.android.ide.eclipse.adt.PreCompilerBuilder 15 | 16 | 17 | 18 | 19 | org.eclipse.jdt.core.javabuilder 20 | 21 | 22 | 23 | 24 | com.android.ide.eclipse.adt.ApkBuilder 25 | 26 | 27 | 28 | 29 | 30 | com.android.ide.eclipse.adt.AndroidNature 31 | org.eclipse.jdt.core.javanature 32 | 33 | 34 | -------------------------------------------------------------------------------- /network/SimpleNet/SimpleNet_Demo/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 3 | org.eclipse.jdt.core.compiler.compliance=1.6 4 | org.eclipse.jdt.core.compiler.source=1.6 5 | -------------------------------------------------------------------------------- /network/SimpleNet/SimpleNet_Demo/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 21 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /network/SimpleNet/SimpleNet_Demo/ic_launcher-web.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simple-android-framework-exchange/simple-android-opensource-framework/bd1ab9e6833a89387cad20596e41156487ffc3c9/network/SimpleNet/SimpleNet_Demo/ic_launcher-web.png -------------------------------------------------------------------------------- /network/SimpleNet/SimpleNet_Demo/proguard-project.txt: -------------------------------------------------------------------------------- 1 | # To enable ProGuard in your project, edit project.properties 2 | # to define the proguard.config property as described in that file. 3 | # 4 | # Add project specific ProGuard rules here. 5 | # By default, the flags in this file are appended to flags specified 6 | # in ${sdk.dir}/tools/proguard/proguard-android.txt 7 | # You can edit the include path and order by changing the ProGuard 8 | # include property in project.properties. 9 | # 10 | # For more details, see 11 | # http://developer.android.com/guide/developing/tools/proguard.html 12 | 13 | # Add any project specific keep options here: 14 | 15 | # If your project uses WebView with JS, uncomment the following 16 | # and specify the fully qualified class name to the JavaScript interface 17 | # class: 18 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 19 | # public *; 20 | #} 21 | -------------------------------------------------------------------------------- /network/SimpleNet/SimpleNet_Demo/project.properties: -------------------------------------------------------------------------------- 1 | # This file is automatically generated by Android Tools. 2 | # Do not modify this file -- YOUR CHANGES WILL BE ERASED! 3 | # 4 | # This file must be checked in Version Control Systems. 5 | # 6 | # To customize properties used by the Ant build system edit 7 | # "ant.properties", and override values to adapt the script to your 8 | # project structure. 9 | # 10 | # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): 11 | #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt 12 | 13 | # Project target. 14 | target=android-21 15 | android.library.reference.1=.. 16 | -------------------------------------------------------------------------------- /network/SimpleNet/SimpleNet_Demo/res/drawable-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simple-android-framework-exchange/simple-android-opensource-framework/bd1ab9e6833a89387cad20596e41156487ffc3c9/network/SimpleNet/SimpleNet_Demo/res/drawable-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /network/SimpleNet/SimpleNet_Demo/res/drawable-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simple-android-framework-exchange/simple-android-opensource-framework/bd1ab9e6833a89387cad20596e41156487ffc3c9/network/SimpleNet/SimpleNet_Demo/res/drawable-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /network/SimpleNet/SimpleNet_Demo/res/drawable-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simple-android-framework-exchange/simple-android-opensource-framework/bd1ab9e6833a89387cad20596e41156487ffc3c9/network/SimpleNet/SimpleNet_Demo/res/drawable-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /network/SimpleNet/SimpleNet_Demo/res/drawable-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simple-android-framework-exchange/simple-android-opensource-framework/bd1ab9e6833a89387cad20596e41156487ffc3c9/network/SimpleNet/SimpleNet_Demo/res/drawable-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /network/SimpleNet/SimpleNet_Demo/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 6 | 7 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /network/SimpleNet/SimpleNet_Demo/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | SimpleNet_Demo 5 | Hello world! 6 | 7 | 8 | -------------------------------------------------------------------------------- /network/SimpleNet/SimpleNet_Demo/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 14 | 15 | 16 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /network/SimpleNet/SimpleNet_Demo/src/com/example/simplenet_demo/MainActivity.java: -------------------------------------------------------------------------------- 1 | 2 | package com.example.simplenet_demo; 3 | 4 | import android.app.Activity; 5 | import android.graphics.Bitmap; 6 | import android.graphics.BitmapFactory; 7 | import android.os.Bundle; 8 | import android.text.Html; 9 | import android.widget.TextView; 10 | 11 | import org.simple.net.base.Request.HttpMethod; 12 | import org.simple.net.base.Request.RequestListener; 13 | import org.simple.net.core.RequestQueue; 14 | import org.simple.net.core.SimpleNet; 15 | import org.simple.net.entity.MultipartEntity; 16 | import org.simple.net.requests.MultipartRequest; 17 | import org.simple.net.requests.StringRequest; 18 | 19 | import java.io.ByteArrayOutputStream; 20 | import java.io.File; 21 | 22 | /** 23 | * SimpleNet简单示例 24 | * 25 | * @author mrsimple 26 | */ 27 | public class MainActivity extends Activity { 28 | 29 | // 1、构建请求队列 30 | RequestQueue mQueue = SimpleNet.newRequestQueue(); 31 | TextView mResultTv; 32 | 33 | @Override 34 | protected void onCreate(Bundle savedInstanceState) { 35 | super.onCreate(savedInstanceState); 36 | setContentView(R.layout.activity_main); 37 | 38 | mResultTv = (TextView) findViewById(R.id.result_tv); 39 | sendStringRequest(); 40 | } 41 | 42 | /** 43 | * 发送GET请求,返回的是String类型的数据, 同理还有{@see JsonRequest}、{@see MultipartRequest} 44 | */ 45 | private void sendStringRequest() { 46 | StringRequest request = new StringRequest(HttpMethod.GET, "http://www.baidu.com", 47 | new RequestListener() { 48 | 49 | @Override 50 | public void onComplete(int stCode, String response, String errMsg) { 51 | mResultTv.setText(Html.fromHtml(response)); 52 | } 53 | }); 54 | 55 | mQueue.addRequest(request); 56 | } 57 | 58 | /** 59 | * 发送MultipartRequest,可以传字符串参数、文件、Bitmap等参数,这种请求为POST类型 60 | */ 61 | protected void sendMultiRequest() { 62 | // 2、创建请求 63 | MultipartRequest multipartRequest = new MultipartRequest("你的url", 64 | new RequestListener() { 65 | @Override 66 | public void onComplete(int stCode, String response, String errMsg) { 67 | // 该方法执行在UI线程 68 | } 69 | }); 70 | 71 | // 3、添加各种参数 72 | // 添加header 73 | multipartRequest.addHeader("header-name", "value"); 74 | 75 | // 通过MultipartEntity来设置参数 76 | MultipartEntity multi = multipartRequest.getMultiPartEntity(); 77 | // 文本参数 78 | multi.addStringPart("location", "模拟的地理位置"); 79 | multi.addStringPart("type", "0"); 80 | 81 | Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); 82 | // 直接从上传Bitmap 83 | multi.addBinaryPart("images", bitmapToBytes(bitmap)); 84 | // 上传文件 85 | multi.addFilePart("imgfile", new File("storage/emulated/0/test.jpg")); 86 | 87 | // 4、将请求添加到队列中 88 | mQueue.addRequest(multipartRequest); 89 | } 90 | 91 | private byte[] bitmapToBytes(Bitmap bitmap) { 92 | ByteArrayOutputStream stream = new ByteArrayOutputStream(); 93 | bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); 94 | return stream.toByteArray(); 95 | } 96 | 97 | @Override 98 | protected void onDestroy() { 99 | mQueue.stop(); 100 | super.onDestroy(); 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /network/SimpleNet/SimpleNet_Detail_1.md: -------------------------------------------------------------------------------- 1 | SimpleNet的Request、Response类与请求队列 2 | --- 3 | -------------------------------------------------------------------------------- /network/SimpleNet/SimpleNet_Detail_2.md: -------------------------------------------------------------------------------- 1 | SimleNet的Http请求分发与执行 2 | --- 3 | -------------------------------------------------------------------------------- /network/SimpleNet/SimpleNet_Detail_3.md: -------------------------------------------------------------------------------- 1 | SimpleNet的请求配置与Response缓存 2 | --- 3 | -------------------------------------------------------------------------------- /network/SimpleNet/images/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simple-android-framework-exchange/simple-android-opensource-framework/bd1ab9e6833a89387cad20596e41156487ffc3c9/network/SimpleNet/images/.DS_Store -------------------------------------------------------------------------------- /network/SimpleNet/images/package-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simple-android-framework-exchange/simple-android-opensource-framework/bd1ab9e6833a89387cad20596e41156487ffc3c9/network/SimpleNet/images/package-2.png -------------------------------------------------------------------------------- /network/SimpleNet/images/package.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simple-android-framework-exchange/simple-android-opensource-framework/bd1ab9e6833a89387cad20596e41156487ffc3c9/network/SimpleNet/images/package.jpeg -------------------------------------------------------------------------------- /network/SimpleNet/images/simple_net_flow.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simple-android-framework-exchange/simple-android-opensource-framework/bd1ab9e6833a89387cad20596e41156487ffc3c9/network/SimpleNet/images/simple_net_flow.jpg -------------------------------------------------------------------------------- /network/SimpleNet/images/uml.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simple-android-framework-exchange/simple-android-opensource-framework/bd1ab9e6833a89387cad20596e41156487ffc3c9/network/SimpleNet/images/uml.jpg -------------------------------------------------------------------------------- /network/SimpleNet/libs/android-support-v4.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simple-android-framework-exchange/simple-android-opensource-framework/bd1ab9e6833a89387cad20596e41156487ffc3c9/network/SimpleNet/libs/android-support-v4.jar -------------------------------------------------------------------------------- /network/SimpleNet/proguard-project.txt: -------------------------------------------------------------------------------- 1 | # To enable ProGuard in your project, edit project.properties 2 | # to define the proguard.config property as described in that file. 3 | # 4 | # Add project specific ProGuard rules here. 5 | # By default, the flags in this file are appended to flags specified 6 | # in ${sdk.dir}/tools/proguard/proguard-android.txt 7 | # You can edit the include path and order by changing the ProGuard 8 | # include property in project.properties. 9 | # 10 | # For more details, see 11 | # http://developer.android.com/guide/developing/tools/proguard.html 12 | 13 | # Add any project specific keep options here: 14 | 15 | # If your project uses WebView with JS, uncomment the following 16 | # and specify the fully qualified class name to the JavaScript interface 17 | # class: 18 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 19 | # public *; 20 | #} 21 | -------------------------------------------------------------------------------- /network/SimpleNet/project.properties: -------------------------------------------------------------------------------- 1 | # This file is automatically generated by Android Tools. 2 | # Do not modify this file -- YOUR CHANGES WILL BE ERASED! 3 | # 4 | # This file must be checked in Version Control Systems. 5 | # 6 | # To customize properties used by the Ant build system edit 7 | # "ant.properties", and override values to adapt the script to your 8 | # project structure. 9 | # 10 | # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): 11 | #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt 12 | 13 | # Project target. 14 | target=android-10 15 | android.library=true 16 | -------------------------------------------------------------------------------- /network/SimpleNet/res/drawable-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simple-android-framework-exchange/simple-android-opensource-framework/bd1ab9e6833a89387cad20596e41156487ffc3c9/network/SimpleNet/res/drawable-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /network/SimpleNet/res/drawable-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simple-android-framework-exchange/simple-android-opensource-framework/bd1ab9e6833a89387cad20596e41156487ffc3c9/network/SimpleNet/res/drawable-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /network/SimpleNet/res/drawable-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simple-android-framework-exchange/simple-android-opensource-framework/bd1ab9e6833a89387cad20596e41156487ffc3c9/network/SimpleNet/res/drawable-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /network/SimpleNet/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | network_framework 4 | 5 | 6 | -------------------------------------------------------------------------------- /network/SimpleNet/simple_net_framework_test/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /network/SimpleNet/simple_net_framework_test/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | simple_net_framework_test 4 | 5 | 6 | simple_net_framework 7 | 8 | 9 | 10 | com.android.ide.eclipse.adt.ResourceManagerBuilder 11 | 12 | 13 | 14 | 15 | com.android.ide.eclipse.adt.PreCompilerBuilder 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javabuilder 21 | 22 | 23 | 24 | 25 | com.android.ide.eclipse.adt.ApkBuilder 26 | 27 | 28 | 29 | 30 | 31 | com.android.ide.eclipse.adt.AndroidNature 32 | org.eclipse.jdt.core.javanature 33 | 34 | 35 | -------------------------------------------------------------------------------- /network/SimpleNet/simple_net_framework_test/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 3 | org.eclipse.jdt.core.compiler.compliance=1.6 4 | org.eclipse.jdt.core.compiler.source=1.6 5 | -------------------------------------------------------------------------------- /network/SimpleNet/simple_net_framework_test/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 | 12 | 13 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /network/SimpleNet/simple_net_framework_test/proguard-project.txt: -------------------------------------------------------------------------------- 1 | # To enable ProGuard in your project, edit project.properties 2 | # to define the proguard.config property as described in that file. 3 | # 4 | # Add project specific ProGuard rules here. 5 | # By default, the flags in this file are appended to flags specified 6 | # in ${sdk.dir}/tools/proguard/proguard-android.txt 7 | # You can edit the include path and order by changing the ProGuard 8 | # include property in project.properties. 9 | # 10 | # For more details, see 11 | # http://developer.android.com/guide/developing/tools/proguard.html 12 | 13 | # Add any project specific keep options here: 14 | 15 | # If your project uses WebView with JS, uncomment the following 16 | # and specify the fully qualified class name to the JavaScript interface 17 | # class: 18 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 19 | # public *; 20 | #} 21 | -------------------------------------------------------------------------------- /network/SimpleNet/simple_net_framework_test/project.properties: -------------------------------------------------------------------------------- 1 | # This file is automatically generated by Android Tools. 2 | # Do not modify this file -- YOUR CHANGES WILL BE ERASED! 3 | # 4 | # This file must be checked in Version Control Systems. 5 | # 6 | # To customize properties used by the Ant build system edit 7 | # "ant.properties", and override values to adapt the script to your 8 | # project structure. 9 | # 10 | # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): 11 | #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt 12 | 13 | # Project target. 14 | target=android-10 15 | android.library.reference.1=.. 16 | -------------------------------------------------------------------------------- /network/SimpleNet/simple_net_framework_test/res/drawable-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simple-android-framework-exchange/simple-android-opensource-framework/bd1ab9e6833a89387cad20596e41156487ffc3c9/network/SimpleNet/simple_net_framework_test/res/drawable-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /network/SimpleNet/simple_net_framework_test/res/drawable-ldpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simple-android-framework-exchange/simple-android-opensource-framework/bd1ab9e6833a89387cad20596e41156487ffc3c9/network/SimpleNet/simple_net_framework_test/res/drawable-ldpi/ic_launcher.png -------------------------------------------------------------------------------- /network/SimpleNet/simple_net_framework_test/res/drawable-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simple-android-framework-exchange/simple-android-opensource-framework/bd1ab9e6833a89387cad20596e41156487ffc3c9/network/SimpleNet/simple_net_framework_test/res/drawable-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /network/SimpleNet/simple_net_framework_test/res/drawable-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simple-android-framework-exchange/simple-android-opensource-framework/bd1ab9e6833a89387cad20596e41156487ffc3c9/network/SimpleNet/simple_net_framework_test/res/drawable-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /network/SimpleNet/simple_net_framework_test/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Simple_net_framework_testTest 5 | 6 | 7 | -------------------------------------------------------------------------------- /network/SimpleNet/simple_net_framework_test/src/com/umeng/network/test/LURCacheTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2014-2015 Umeng, Inc 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package com.umeng.network.test; 26 | 27 | import android.support.v4.util.LruCache; 28 | import android.test.AndroidTestCase; 29 | 30 | import org.apache.http.ProtocolVersion; 31 | import org.apache.http.StatusLine; 32 | import org.simple.net.base.Request; 33 | import org.simple.net.base.Response; 34 | import org.simple.net.base.Request.HttpMethod; 35 | import org.simple.net.requests.StringRequest; 36 | 37 | public class LURCacheTest extends AndroidTestCase { 38 | 39 | /** 40 | * Reponse缓存 41 | */ 42 | private LruCache, Response> mResponseCache; 43 | 44 | protected void setUp() throws Exception { 45 | super.setUp(); 46 | initCache(); 47 | } 48 | 49 | protected void tearDown() throws Exception { 50 | super.tearDown(); 51 | } 52 | 53 | private void initCache() { 54 | mResponseCache = new LruCache, Response>(108 * 1024); 55 | } 56 | 57 | public void testMultiRequestCache() { 58 | 59 | for (int i = 0; i < 20; i++) { 60 | StringRequest request = new StringRequest(HttpMethod.GET, "http://url" + i, null); 61 | request.getParams().put("key-" + i, "value-1"); 62 | request.getHeaders().put("header-" + i, "header-" + i); 63 | Response response = new Response(mStatusLine); 64 | mResponseCache.put(request, response); 65 | } 66 | 67 | assertEquals(20, mResponseCache.size()); 68 | 69 | } 70 | 71 | public void testMultiRequestWithSame() { 72 | 73 | for (int i = 0; i < 20; i++) { 74 | StringRequest request = new StringRequest(HttpMethod.GET, "http://url", null); 75 | request.getParams().put("key-1", "value-1"); 76 | request.getHeaders().put("header-1", "header-1"); 77 | Response response = new Response(mStatusLine); 78 | mResponseCache.put(request, response); 79 | } 80 | 81 | assertEquals(1, mResponseCache.size()); 82 | 83 | } 84 | 85 | StatusLine mStatusLine = new StatusLine() { 86 | 87 | @Override 88 | public int getStatusCode() { 89 | return 0; 90 | } 91 | 92 | @Override 93 | public String getReasonPhrase() { 94 | return "msg"; 95 | } 96 | 97 | @Override 98 | public ProtocolVersion getProtocolVersion() { 99 | return new ProtocolVersion("http", 1, 1); 100 | } 101 | }; 102 | 103 | } 104 | -------------------------------------------------------------------------------- /network/SimpleNet/simple_net_framework_test/src/com/umeng/network/test/RequestQueueTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2014-2015 Umeng, Inc 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package com.umeng.network.test; 26 | 27 | import android.test.AndroidTestCase; 28 | 29 | import org.simple.net.base.Request.HttpMethod; 30 | import org.simple.net.base.Request.RequestListener; 31 | import org.simple.net.core.RequestQueue; 32 | import org.simple.net.core.SimpleNet; 33 | import org.simple.net.requests.StringRequest; 34 | 35 | public class RequestQueueTest extends AndroidTestCase { 36 | 37 | RequestQueue mQueue = SimpleNet.newRequestQueue(); 38 | 39 | protected void setUp() throws Exception { 40 | super.setUp(); 41 | } 42 | 43 | protected void tearDown() throws Exception { 44 | super.tearDown(); 45 | mQueue.clear(); 46 | } 47 | 48 | public void testMultiRequests() { 49 | 50 | for (int i = 0; i < 10; i++) { 51 | StringRequest request = new StringRequest(HttpMethod.GET, "http://myhost.com", null); 52 | mQueue.addRequest(request); 53 | } 54 | 55 | assertEquals(1, mQueue.getAllRequests().size()); 56 | 57 | } 58 | 59 | public void testMultiRequestsWithListeners() { 60 | // 添加lisener 61 | for (int i = 0; i < 10; i++) { 62 | StringRequest request = new StringRequest(HttpMethod.GET, "http://myhost.com", 63 | new RequestListener() { 64 | 65 | @Override 66 | public void onComplete(int stCode, String response, String errMsg) { 67 | 68 | } 69 | }); 70 | mQueue.addRequest(request); 71 | } 72 | 73 | assertEquals(1, mQueue.getAllRequests().size()); 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /network/SimpleNet/src/org/simple/net/base/Request.java: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.simple.net.base; 26 | 27 | import android.util.Log; 28 | 29 | import java.io.UnsupportedEncodingException; 30 | import java.net.URLEncoder; 31 | import java.util.HashMap; 32 | import java.util.Map; 33 | 34 | /** 35 | * 网络请求类. 注意GET和DELETE不能传递参数,因为其请求的性质所致,用户可以将参数构建到url后传递进来到Request中. 36 | * 37 | * @author mrsimple 38 | * @param T为请求返回的数据类型 39 | */ 40 | public abstract class Request implements Comparable> { 41 | 42 | /** 43 | * http request method enum. 44 | * 45 | * @author mrsimple 46 | */ 47 | public static enum HttpMethod { 48 | GET("GET"), 49 | POST("POST"), 50 | PUT("PUT"), 51 | DELETE("DELETE"); 52 | 53 | /** http request type */ 54 | private String mHttpMethod = ""; 55 | 56 | private HttpMethod(String method) { 57 | mHttpMethod = method; 58 | } 59 | 60 | @Override 61 | public String toString() { 62 | return mHttpMethod; 63 | } 64 | } 65 | 66 | /** 67 | * 优先级枚举 68 | * 69 | * @author mrsimple 70 | */ 71 | public static enum Priority { 72 | LOW, 73 | NORMAL, 74 | HIGN, 75 | IMMEDIATE 76 | } 77 | 78 | /** 79 | * Default encoding for POST or PUT parameters. See 80 | * {@link #getParamsEncoding()}. 81 | */ 82 | public static final String DEFAULT_PARAMS_ENCODING = "UTF-8"; 83 | /** 84 | * Default Content-type 85 | */ 86 | public final static String HEADER_CONTENT_TYPE = "Content-Type"; 87 | /** 88 | * 请求序列号 89 | */ 90 | protected int mSerialNum = 0; 91 | /** 92 | * 优先级默认设置为Normal 93 | */ 94 | protected Priority mPriority = Priority.NORMAL; 95 | /** 96 | * 是否取消该请求 97 | */ 98 | protected boolean isCancel = false; 99 | 100 | /** 该请求是否应该缓存 */ 101 | private boolean mShouldCache = true; 102 | /** 103 | * 请求Listener 104 | */ 105 | protected RequestListener mRequestListener; 106 | /** 107 | * 请求的url 108 | */ 109 | private String mUrl = ""; 110 | /** 111 | * 请求的方法 112 | */ 113 | HttpMethod mHttpMethod = HttpMethod.GET; 114 | 115 | /** 116 | * 请求的header 117 | */ 118 | private Map mHeaders = new HashMap(); 119 | /** 120 | * 请求参数 121 | */ 122 | private Map mBodyParams = new HashMap(); 123 | 124 | /** 125 | * @param method 126 | * @param url 127 | * @param listener 128 | */ 129 | public Request(HttpMethod method, String url, RequestListener listener) { 130 | mHttpMethod = method; 131 | mUrl = url; 132 | mRequestListener = listener; 133 | } 134 | 135 | public void addHeader(String name, String value) { 136 | mHeaders.put(name, value); 137 | } 138 | 139 | /** 140 | * 从原生的网络请求中解析结果 141 | * 142 | * @param response 143 | * @return 144 | */ 145 | public abstract T parseResponse(Response response); 146 | 147 | /** 148 | * 处理Response,该方法运行在UI线程. 149 | * 150 | * @param response 151 | */ 152 | public final void deliveryResponse(Response response) { 153 | T result = parseResponse(response); 154 | if (mRequestListener != null) { 155 | int stCode = response != null ? response.getStatusCode() : -1; 156 | String msg = response != null ? response.getMessage() : "unkown error"; 157 | Log.e("", "### 执行回调 : stCode = " + stCode + ", result : " + result + ", err : " + msg); 158 | mRequestListener.onComplete(stCode, result, msg); 159 | } 160 | } 161 | 162 | public String getUrl() { 163 | return mUrl; 164 | } 165 | 166 | public RequestListener getRequestListener() { 167 | return mRequestListener; 168 | } 169 | 170 | public int getSerialNumber() { 171 | return mSerialNum; 172 | } 173 | 174 | public void setSerialNumber(int mSerialNum) { 175 | this.mSerialNum = mSerialNum; 176 | } 177 | 178 | public Priority getPriority() { 179 | return mPriority; 180 | } 181 | 182 | public void setPriority(Priority mPriority) { 183 | this.mPriority = mPriority; 184 | } 185 | 186 | protected String getParamsEncoding() { 187 | return DEFAULT_PARAMS_ENCODING; 188 | } 189 | 190 | public String getBodyContentType() { 191 | return "application/x-www-form-urlencoded; charset=" + getParamsEncoding(); 192 | } 193 | 194 | public HttpMethod getHttpMethod() { 195 | return mHttpMethod; 196 | } 197 | 198 | public Map getHeaders() { 199 | return mHeaders; 200 | } 201 | 202 | public Map getParams() { 203 | return mBodyParams; 204 | } 205 | 206 | public boolean isHttps() { 207 | return mUrl.startsWith("https"); 208 | } 209 | 210 | /** 211 | * 该请求是否应该缓存 212 | * 213 | * @param shouldCache 214 | */ 215 | public void setShouldCache(boolean shouldCache) { 216 | this.mShouldCache = shouldCache; 217 | } 218 | 219 | public boolean shouldCache() { 220 | return mShouldCache; 221 | } 222 | 223 | public void cancel() { 224 | isCancel = true; 225 | } 226 | 227 | public boolean isCanceled() { 228 | return isCancel; 229 | } 230 | 231 | /** 232 | * Returns the raw POST or PUT body to be sent. 233 | * 234 | * @throws AuthFailureError in the event of auth failure 235 | */ 236 | public byte[] getBody() { 237 | Map params = getParams(); 238 | if (params != null && params.size() > 0) { 239 | return encodeParameters(params, getParamsEncoding()); 240 | } 241 | return null; 242 | } 243 | 244 | /** 245 | * Converts params into an application/x-www-form-urlencoded 246 | * encoded string. 247 | */ 248 | private byte[] encodeParameters(Map params, String paramsEncoding) { 249 | StringBuilder encodedParams = new StringBuilder(); 250 | try { 251 | for (Map.Entry entry : params.entrySet()) { 252 | encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding)); 253 | encodedParams.append('='); 254 | encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding)); 255 | encodedParams.append('&'); 256 | } 257 | return encodedParams.toString().getBytes(paramsEncoding); 258 | } catch (UnsupportedEncodingException uee) { 259 | throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee); 260 | } 261 | } 262 | 263 | @Override 264 | public int compareTo(Request another) { 265 | Priority myPriority = this.getPriority(); 266 | Priority anotherPriority = another.getPriority(); 267 | // 如果优先级相等,那么按照添加到队列的序列号顺序来执行 268 | return myPriority.equals(anotherPriority) ? this.getSerialNumber() 269 | - another.getSerialNumber() 270 | : myPriority.ordinal() - anotherPriority.ordinal(); 271 | } 272 | 273 | @Override 274 | public int hashCode() { 275 | final int prime = 31; 276 | int result = 1; 277 | result = prime * result + ((mHeaders == null) ? 0 : mHeaders.hashCode()); 278 | result = prime * result + ((mHttpMethod == null) ? 0 : mHttpMethod.hashCode()); 279 | result = prime * result + ((mBodyParams == null) ? 0 : mBodyParams.hashCode()); 280 | result = prime * result + ((mPriority == null) ? 0 : mPriority.hashCode()); 281 | result = prime * result + (mShouldCache ? 1231 : 1237); 282 | result = prime * result + ((mUrl == null) ? 0 : mUrl.hashCode()); 283 | return result; 284 | } 285 | 286 | @Override 287 | public boolean equals(Object obj) { 288 | if (this == obj) 289 | return true; 290 | if (obj == null) 291 | return false; 292 | if (getClass() != obj.getClass()) 293 | return false; 294 | Request other = (Request) obj; 295 | if (mHeaders == null) { 296 | if (other.mHeaders != null) 297 | return false; 298 | } else if (!mHeaders.equals(other.mHeaders)) 299 | return false; 300 | if (mHttpMethod != other.mHttpMethod) 301 | return false; 302 | if (mBodyParams == null) { 303 | if (other.mBodyParams != null) 304 | return false; 305 | } else if (!mBodyParams.equals(other.mBodyParams)) 306 | return false; 307 | if (mPriority != other.mPriority) 308 | return false; 309 | if (mShouldCache != other.mShouldCache) 310 | return false; 311 | if (mUrl == null) { 312 | if (other.mUrl != null) 313 | return false; 314 | } else if (!mUrl.equals(other.mUrl)) 315 | return false; 316 | return true; 317 | } 318 | 319 | /** 320 | * 网络请求Listener 321 | * 322 | * @author mrsimple 323 | * @param 请求的response类型 324 | */ 325 | public static interface RequestListener { 326 | /** 327 | * 请求完成的回调 328 | * 329 | * @param response 330 | */ 331 | public void onComplete(int stCode, T response, String errMsg); 332 | } 333 | } 334 | -------------------------------------------------------------------------------- /network/SimpleNet/src/org/simple/net/base/Response.java: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.simple.net.base; 26 | 27 | import org.apache.http.HttpEntity; 28 | import org.apache.http.ProtocolVersion; 29 | import org.apache.http.StatusLine; 30 | import org.apache.http.message.BasicHttpResponse; 31 | import org.apache.http.util.EntityUtils; 32 | 33 | import java.io.IOException; 34 | 35 | /** 36 | * 请求结果类,继承自BasicHttpResponse,将结果存储在rawData中. 37 | * 38 | * @author mrsimple 39 | */ 40 | public class Response extends BasicHttpResponse { 41 | 42 | public byte[] rawData = new byte[0]; 43 | 44 | public Response(StatusLine statusLine) { 45 | super(statusLine); 46 | } 47 | 48 | public Response(ProtocolVersion ver, int code, String reason) { 49 | super(ver, code, reason); 50 | } 51 | 52 | @Override 53 | public void setEntity(HttpEntity entity) { 54 | super.setEntity(entity); 55 | rawData = entityToBytes(getEntity()); 56 | } 57 | 58 | public byte[] getRawData() { 59 | return rawData; 60 | } 61 | 62 | public int getStatusCode() { 63 | return getStatusLine().getStatusCode(); 64 | } 65 | 66 | public String getMessage() { 67 | return getStatusLine().getReasonPhrase(); 68 | } 69 | 70 | /** Reads the contents of HttpEntity into a byte[]. */ 71 | private byte[] entityToBytes(HttpEntity entity) { 72 | try { 73 | return EntityUtils.toByteArray(entity); 74 | } catch (IOException e) { 75 | e.printStackTrace(); 76 | } 77 | return new byte[0]; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /network/SimpleNet/src/org/simple/net/cache/Cache.java: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.simple.net.cache; 26 | 27 | /** 28 | * 请求缓存接口 29 | * 30 | * @author mrsimple 31 | * @param key的类型 32 | * @param value类型 33 | */ 34 | public interface Cache { 35 | 36 | public V get(K key); 37 | 38 | public void put(K key, V value); 39 | 40 | public void remove(K key); 41 | 42 | } 43 | -------------------------------------------------------------------------------- /network/SimpleNet/src/org/simple/net/cache/LruMemCache.java: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.simple.net.cache; 26 | 27 | import android.support.v4.util.LruCache; 28 | 29 | import org.simple.net.base.Response; 30 | 31 | /** 32 | * 将请求结果缓存到内存中 33 | * 34 | * @author mrsimple 35 | */ 36 | public class LruMemCache implements Cache { 37 | 38 | /** 39 | * Reponse缓存 40 | */ 41 | private LruCache mResponseCache; 42 | 43 | public LruMemCache() { 44 | // 计算可使用的最大内存 45 | final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); 46 | 47 | // 取八分之一的可用内存作为缓存 48 | final int cacheSize = maxMemory / 8; 49 | mResponseCache = new LruCache(cacheSize) { 50 | 51 | @Override 52 | protected int sizeOf(String key, Response response) { 53 | return response.rawData.length / 1024; 54 | } 55 | }; 56 | 57 | } 58 | 59 | @Override 60 | public Response get(String key) { 61 | return mResponseCache.get(key); 62 | } 63 | 64 | @Override 65 | public void put(String key, Response response) { 66 | mResponseCache.put(key, response); 67 | } 68 | 69 | @Override 70 | public void remove(String key) { 71 | mResponseCache.remove(key); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /network/SimpleNet/src/org/simple/net/config/HttpClientConfig.java: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.simple.net.config; 26 | 27 | import org.apache.http.conn.ssl.SSLSocketFactory; 28 | 29 | /** 30 | * 这是针对于使用HttpClientStack执行请求时为https请求配置的SSLSocketFactory类 31 | * 32 | * @author mrsimple 33 | */ 34 | public class HttpClientConfig extends HttpConfig { 35 | private static HttpClientConfig sConfig = new HttpClientConfig(); 36 | SSLSocketFactory mSslSocketFactory; 37 | 38 | private HttpClientConfig() { 39 | 40 | } 41 | 42 | public static HttpClientConfig getConfig() { 43 | return sConfig; 44 | } 45 | 46 | /** 47 | * 配置https请求的SSLSocketFactory与HostnameVerifier 48 | * 49 | * @param sslSocketFactory 50 | * @param hostnameVerifier 51 | */ 52 | public void setHttpsConfig(SSLSocketFactory sslSocketFactory) { 53 | mSslSocketFactory = sslSocketFactory; 54 | } 55 | 56 | public SSLSocketFactory getSocketFactory() { 57 | return mSslSocketFactory; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /network/SimpleNet/src/org/simple/net/config/HttpConfig.java: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.simple.net.config; 26 | 27 | /** 28 | * http配置类 29 | * 30 | * @author mrsimple 31 | */ 32 | public abstract class HttpConfig { 33 | public String userAgent = "default"; 34 | public int soTimeOut = 10000; 35 | public int connTimeOut = 10000; 36 | } 37 | -------------------------------------------------------------------------------- /network/SimpleNet/src/org/simple/net/config/HttpUrlConnConfig.java: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.simple.net.config; 26 | 27 | import javax.net.ssl.HostnameVerifier; 28 | import javax.net.ssl.SSLSocketFactory; 29 | 30 | /** 31 | * 这是针对于使用HttpUrlStack执行请求时为https请求设置的SSLSocketFactory和HostnameVerifier的配置类,参考 32 | * http://blog.csdn.net/xyz_lmn/article/details/8027334,http://www.cnblogs.com/ 33 | * vus520/archive/2012/09/07/2674725.html, 34 | * 35 | * @author mrsimple 36 | */ 37 | public class HttpUrlConnConfig extends HttpConfig { 38 | 39 | private static HttpUrlConnConfig sConfig = new HttpUrlConnConfig(); 40 | 41 | private SSLSocketFactory mSslSocketFactory = null; 42 | private HostnameVerifier mHostnameVerifier = null; 43 | 44 | private HttpUrlConnConfig() { 45 | } 46 | 47 | public static HttpUrlConnConfig getConfig() { 48 | return sConfig; 49 | } 50 | 51 | /** 52 | * 配置https请求的SSLSocketFactory与HostnameVerifier 53 | * 54 | * @param sslSocketFactory 55 | * @param hostnameVerifier 56 | */ 57 | public void setHttpsConfig(SSLSocketFactory sslSocketFactory, 58 | HostnameVerifier hostnameVerifier) { 59 | mSslSocketFactory = sslSocketFactory; 60 | mHostnameVerifier = hostnameVerifier; 61 | } 62 | 63 | public HostnameVerifier getHostnameVerifier() { 64 | return mHostnameVerifier; 65 | } 66 | 67 | public SSLSocketFactory getSslSocketFactory() { 68 | return mSslSocketFactory; 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /network/SimpleNet/src/org/simple/net/core/NetworkExecutor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2014-2015 bboyfeiyu@gmail.com 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.simple.net.core; 26 | 27 | import android.util.Log; 28 | 29 | import org.simple.net.base.Request; 30 | import org.simple.net.base.Response; 31 | import org.simple.net.cache.Cache; 32 | import org.simple.net.cache.LruMemCache; 33 | import org.simple.net.httpstacks.HttpStack; 34 | 35 | import java.util.concurrent.BlockingQueue; 36 | 37 | /** 38 | * 网络请求Executor,继承自Thread,从网络请求队列中循环读取请求并且执行 39 | * 40 | * @author mrsimple 41 | */ 42 | final class NetworkExecutor extends Thread { 43 | 44 | /** 45 | * 网络请求队列 46 | */ 47 | private BlockingQueue> mRequestQueue; 48 | /** 49 | * 网络请求栈 50 | */ 51 | private HttpStack mHttpStack; 52 | /** 53 | * 结果分发器,将结果投递到主线程 54 | */ 55 | private static ResponseDelivery mResponseDelivery = new ResponseDelivery(); 56 | /** 57 | * 请求缓存 58 | */ 59 | private static Cache mReqCache = new LruMemCache(); 60 | /** 61 | * 是否停止 62 | */ 63 | private boolean isStop = false; 64 | 65 | public NetworkExecutor(BlockingQueue> queue, HttpStack httpStack) { 66 | mRequestQueue = queue; 67 | mHttpStack = httpStack; 68 | } 69 | 70 | @Override 71 | public void run() { 72 | try { 73 | while (!isStop) { 74 | final Request request = mRequestQueue.take(); 75 | if (request.isCanceled()) { 76 | Log.d("### ", "### 取消执行了"); 77 | continue; 78 | } 79 | Response response = null; 80 | if (isUseCache(request)) { 81 | // 从缓存中取 82 | response = mReqCache.get(request.getUrl()); 83 | } else { 84 | // 从网络上获取数据 85 | response = mHttpStack.performRequest(request); 86 | // 如果该请求需要缓存,那么请求成功则缓存到mResponseCache中 87 | if (request.shouldCache() && isSuccess(response)) { 88 | mReqCache.put(request.getUrl(), response); 89 | } 90 | } 91 | 92 | // 分发请求结果 93 | mResponseDelivery.deliveryResponse(request, response); 94 | } 95 | } catch (InterruptedException e) { 96 | Log.i("", "### 请求分发器退出"); 97 | } 98 | 99 | } 100 | 101 | private boolean isSuccess(Response response) { 102 | return response != null && response.getStatusCode() == 200; 103 | } 104 | 105 | private boolean isUseCache(Request request) { 106 | return request.shouldCache() && mReqCache.get(request.getUrl()) != null; 107 | } 108 | 109 | public void quit() { 110 | isStop = true; 111 | interrupt(); 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /network/SimpleNet/src/org/simple/net/core/RequestQueue.java: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.simple.net.core; 26 | 27 | import android.util.Log; 28 | 29 | import org.simple.net.base.Request; 30 | import org.simple.net.httpstacks.HttpStack; 31 | import org.simple.net.httpstacks.HttpStackFactory; 32 | 33 | import java.util.concurrent.BlockingQueue; 34 | import java.util.concurrent.PriorityBlockingQueue; 35 | import java.util.concurrent.atomic.AtomicInteger; 36 | 37 | /** 38 | * 请求队列, 使用优先队列,使得请求可以按照优先级进行处理. [ Thread Safe ] 39 | * 40 | * @author mrsimple 41 | */ 42 | public final class RequestQueue { 43 | /** 44 | * 请求队列 [ Thread-safe ] 45 | */ 46 | private BlockingQueue> mRequestQueue = new PriorityBlockingQueue>(); 47 | /** 48 | * 请求的序列化生成器 49 | */ 50 | private AtomicInteger mSerialNumGenerator = new AtomicInteger(0); 51 | 52 | /** 53 | * 默认的核心数 54 | */ 55 | public static int DEFAULT_CORE_NUMS = Runtime.getRuntime().availableProcessors() + 1; 56 | /** 57 | * CPU核心数 + 1个分发线程数 58 | */ 59 | private int mDispatcherNums = DEFAULT_CORE_NUMS; 60 | /** 61 | * NetworkExecutor,执行网络请求的线程 62 | */ 63 | private NetworkExecutor[] mDispatchers = null; 64 | /** 65 | * Http请求的真正执行者 66 | */ 67 | private HttpStack mHttpStack; 68 | 69 | /** 70 | * @param coreNums 线程核心数 71 | * @param httpStack http执行器 72 | */ 73 | protected RequestQueue(int coreNums, HttpStack httpStack) { 74 | mDispatcherNums = coreNums; 75 | mHttpStack = httpStack != null ? httpStack : HttpStackFactory.createHttpStack(); 76 | } 77 | 78 | /** 79 | * 启动NetworkExecutor 80 | */ 81 | private final void startNetworkExecutors() { 82 | mDispatchers = new NetworkExecutor[mDispatcherNums]; 83 | for (int i = 0; i < mDispatcherNums; i++) { 84 | mDispatchers[i] = new NetworkExecutor(mRequestQueue, mHttpStack); 85 | mDispatchers[i].start(); 86 | } 87 | } 88 | 89 | public void start() { 90 | stop(); 91 | startNetworkExecutors(); 92 | } 93 | 94 | /** 95 | * 停止NetworkExecutor 96 | */ 97 | public void stop() { 98 | if (mDispatchers != null && mDispatchers.length > 0) { 99 | for (int i = 0; i < mDispatchers.length; i++) { 100 | mDispatchers[i].quit(); 101 | } 102 | } 103 | } 104 | 105 | /** 106 | * 不能重复添加请求 107 | * 108 | * @param request 109 | */ 110 | public void addRequest(Request request) { 111 | if (!mRequestQueue.contains(request)) { 112 | request.setSerialNumber(this.generateSerialNumber()); 113 | mRequestQueue.add(request); 114 | } else { 115 | Log.d("", "### 请求队列中已经含有"); 116 | } 117 | } 118 | 119 | public void clear() { 120 | mRequestQueue.clear(); 121 | } 122 | 123 | public BlockingQueue> getAllRequests() { 124 | return mRequestQueue; 125 | } 126 | 127 | /** 128 | * 为每个请求生成一个系列号 129 | * 130 | * @return 序列号 131 | */ 132 | private int generateSerialNumber() { 133 | return mSerialNumGenerator.incrementAndGet(); 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /network/SimpleNet/src/org/simple/net/core/ResponseDelivery.java: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.simple.net.core; 26 | 27 | import android.os.Handler; 28 | import android.os.Looper; 29 | 30 | import org.simple.net.base.Request; 31 | import org.simple.net.base.Response; 32 | 33 | import java.util.concurrent.Executor; 34 | 35 | /** 36 | * 请求结果投递类,将请求结果投递给UI线程 37 | * 38 | * @author mrsimple 39 | */ 40 | class ResponseDelivery implements Executor { 41 | 42 | /** 43 | * 主线程的hander 44 | */ 45 | Handler mResponseHandler = new Handler(Looper.getMainLooper()); 46 | 47 | /** 48 | * 处理请求结果,将其执行在UI线程 49 | * 50 | * @param request 51 | * @param response 52 | */ 53 | public void deliveryResponse(final Request request, final Response response) { 54 | Runnable respRunnable = new Runnable() { 55 | 56 | @Override 57 | public void run() { 58 | request.deliveryResponse(response); 59 | } 60 | }; 61 | 62 | execute(respRunnable); 63 | } 64 | 65 | @Override 66 | public void execute(Runnable command) { 67 | mResponseHandler.post(command); 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /network/SimpleNet/src/org/simple/net/core/SimpleNet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2014-2015 bboyfeiyu@gmail.com 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.simple.net.core; 26 | 27 | import org.simple.net.httpstacks.HttpStack; 28 | 29 | /** 30 | * SimpleNet入口 31 | * @author mrsimple 32 | */ 33 | public final class SimpleNet { 34 | /** 35 | * 创建一个请求队列,NetworkExecutor数量为默认的数量 36 | * 37 | * @return 38 | */ 39 | public static RequestQueue newRequestQueue() { 40 | return newRequestQueue(RequestQueue.DEFAULT_CORE_NUMS); 41 | } 42 | 43 | /** 44 | * 创建一个请求队列,NetworkExecutor数量为coreNums 45 | * 46 | * @param coreNums 47 | * @return 48 | */ 49 | public static RequestQueue newRequestQueue(int coreNums) { 50 | return newRequestQueue(coreNums, null); 51 | } 52 | 53 | /** 54 | * 创建一个请求队列,NetworkExecutor数量为coreNums 55 | * 56 | * @param coreNums 线程数量 57 | * @param httpStack 网络执行者 58 | * @return 59 | */ 60 | public static RequestQueue newRequestQueue(int coreNums, HttpStack httpStack) { 61 | RequestQueue queue = new RequestQueue(Math.max(0, coreNums), httpStack); 62 | queue.start(); 63 | return queue; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /network/SimpleNet/src/org/simple/net/entity/MultipartEntity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.simple.net.entity; 26 | 27 | import android.text.TextUtils; 28 | 29 | import org.apache.http.Header; 30 | import org.apache.http.HttpEntity; 31 | import org.apache.http.message.BasicHeader; 32 | 33 | import java.io.ByteArrayInputStream; 34 | import java.io.ByteArrayOutputStream; 35 | import java.io.Closeable; 36 | import java.io.File; 37 | import java.io.FileInputStream; 38 | import java.io.IOException; 39 | import java.io.InputStream; 40 | import java.io.OutputStream; 41 | import java.util.Random; 42 | 43 | /** 44 | * POST报文格式请参考博客 : http://blog.csdn.net/bboyfeiyu/article/details/41863951. 45 | *

46 | * Android中的多参数类型的Entity实体类,用户可以使用该类来上传文件、文本参数、二进制参数, 47 | * 不需要依赖于httpmime.jar来实现上传文件的功能. 48 | *

49 | * 50 | * @author mrsimple 51 | */ 52 | public class MultipartEntity implements HttpEntity { 53 | 54 | private final static char[] MULTIPART_CHARS = "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" 55 | .toCharArray(); 56 | /** 57 | * 换行符 58 | */ 59 | private final String NEW_LINE_STR = "\r\n"; 60 | private final String CONTENT_TYPE = "Content-Type: "; 61 | private final String CONTENT_DISPOSITION = "Content-Disposition: "; 62 | /** 63 | * 文本参数和字符集 64 | */ 65 | private final String TYPE_TEXT_CHARSET = "text/plain; charset=UTF-8"; 66 | 67 | /** 68 | * 字节流参数 69 | */ 70 | private final String TYPE_OCTET_STREAM = "application/octet-stream"; 71 | /** 72 | * 二进制参数 73 | */ 74 | private final byte[] BINARY_ENCODING = "Content-Transfer-Encoding: binary\r\n\r\n".getBytes(); 75 | /** 76 | * 文本参数 77 | */ 78 | private final byte[] BIT_ENCODING = "Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes(); 79 | 80 | /** 81 | * 分隔符 82 | */ 83 | private String mBoundary = null; 84 | /** 85 | * 输出流 86 | */ 87 | ByteArrayOutputStream mOutputStream = new ByteArrayOutputStream(); 88 | 89 | public MultipartEntity() { 90 | this.mBoundary = generateBoundary(); 91 | } 92 | 93 | /** 94 | * 生成分隔符 95 | * 96 | * @return 97 | */ 98 | private final String generateBoundary() { 99 | final StringBuffer buf = new StringBuffer(); 100 | final Random rand = new Random(); 101 | for (int i = 0; i < 30; i++) { 102 | buf.append(MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]); 103 | } 104 | return buf.toString(); 105 | } 106 | 107 | /** 108 | * 参数开头的分隔符 109 | * 110 | * @throws IOException 111 | */ 112 | private void writeFirstBoundary() throws IOException { 113 | mOutputStream.write(("--" + mBoundary + "\r\n").getBytes()); 114 | } 115 | 116 | /** 117 | * 添加文本参数 118 | * 119 | * @param key 120 | * @param value 121 | */ 122 | public void addStringPart(final String paramName, final String value) { 123 | writeToOutputStream(paramName, value.getBytes(), TYPE_TEXT_CHARSET, BIT_ENCODING, ""); 124 | } 125 | 126 | /** 127 | * 将数据写入到输出流中 128 | * 129 | * @param key 130 | * @param rawData 131 | * @param type 132 | * @param encodingBytes 133 | * @param fileName 134 | */ 135 | private void writeToOutputStream(String paramName, byte[] rawData, String type, 136 | byte[] encodingBytes, 137 | String fileName) { 138 | try { 139 | writeFirstBoundary(); 140 | mOutputStream.write((CONTENT_TYPE + type + NEW_LINE_STR).getBytes()); 141 | mOutputStream 142 | .write(getContentDispositionBytes(paramName, fileName)); 143 | mOutputStream.write(encodingBytes); 144 | mOutputStream.write(rawData); 145 | mOutputStream.write(NEW_LINE_STR.getBytes()); 146 | } catch (final IOException e) { 147 | e.printStackTrace(); 148 | } 149 | } 150 | 151 | /** 152 | * 添加二进制参数, 例如Bitmap的字节流参数 153 | * 154 | * @param key 155 | * @param rawData 156 | */ 157 | public void addBinaryPart(String paramName, final byte[] rawData) { 158 | writeToOutputStream(paramName, rawData, TYPE_OCTET_STREAM, BINARY_ENCODING, "no-file"); 159 | } 160 | 161 | /** 162 | * 添加文件参数,可以实现文件上传功能 163 | * 164 | * @param key 165 | * @param file 166 | */ 167 | public void addFilePart(final String key, final File file) { 168 | InputStream fin = null; 169 | try { 170 | fin = new FileInputStream(file); 171 | writeFirstBoundary(); 172 | final String type = CONTENT_TYPE + TYPE_OCTET_STREAM + NEW_LINE_STR; 173 | mOutputStream.write(getContentDispositionBytes(key, file.getName())); 174 | mOutputStream.write(type.getBytes()); 175 | mOutputStream.write(BINARY_ENCODING); 176 | 177 | final byte[] tmp = new byte[4096]; 178 | int len = 0; 179 | while ((len = fin.read(tmp)) != -1) { 180 | mOutputStream.write(tmp, 0, len); 181 | } 182 | mOutputStream.flush(); 183 | } catch (final IOException e) { 184 | e.printStackTrace(); 185 | } finally { 186 | closeSilently(fin); 187 | } 188 | } 189 | 190 | private void closeSilently(Closeable closeable) { 191 | try { 192 | if (closeable != null) { 193 | closeable.close(); 194 | } 195 | } catch (final IOException e) { 196 | e.printStackTrace(); 197 | } 198 | } 199 | 200 | private byte[] getContentDispositionBytes(String paramName, String fileName) { 201 | StringBuilder stringBuilder = new StringBuilder(); 202 | stringBuilder.append(CONTENT_DISPOSITION + "form-data; name=\"" + paramName + "\""); 203 | // 文本参数没有filename参数,设置为空即可 204 | if (!TextUtils.isEmpty(fileName)) { 205 | stringBuilder.append("; filename=\"" 206 | + fileName + "\""); 207 | } 208 | 209 | return stringBuilder.append(NEW_LINE_STR).toString().getBytes(); 210 | } 211 | 212 | @Override 213 | public long getContentLength() { 214 | return mOutputStream.toByteArray().length; 215 | } 216 | 217 | @Override 218 | public Header getContentType() { 219 | return new BasicHeader("Content-Type", "multipart/form-data; boundary=" + mBoundary); 220 | } 221 | 222 | @Override 223 | public boolean isChunked() { 224 | return false; 225 | } 226 | 227 | @Override 228 | public boolean isRepeatable() { 229 | return false; 230 | } 231 | 232 | @Override 233 | public boolean isStreaming() { 234 | return false; 235 | } 236 | 237 | @Override 238 | public void writeTo(final OutputStream outstream) throws IOException { 239 | // 参数最末尾的结束符 240 | final String endString = "--" + mBoundary + "--\r\n"; 241 | // 写入结束符 242 | mOutputStream.write(endString.getBytes()); 243 | // 244 | outstream.write(mOutputStream.toByteArray()); 245 | } 246 | 247 | @Override 248 | public Header getContentEncoding() { 249 | return null; 250 | } 251 | 252 | @Override 253 | public void consumeContent() throws IOException, 254 | UnsupportedOperationException { 255 | if (isStreaming()) { 256 | throw new UnsupportedOperationException( 257 | "Streaming entity does not implement #consumeContent()"); 258 | } 259 | } 260 | 261 | @Override 262 | public InputStream getContent() { 263 | return new ByteArrayInputStream(mOutputStream.toByteArray()); 264 | } 265 | } 266 | -------------------------------------------------------------------------------- /network/SimpleNet/src/org/simple/net/httpstacks/HttpClientStack.java: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.simple.net.httpstacks; 26 | 27 | import android.net.http.AndroidHttpClient; 28 | 29 | import org.apache.http.HttpEntity; 30 | import org.apache.http.HttpResponse; 31 | import org.apache.http.client.HttpClient; 32 | import org.apache.http.client.methods.HttpDelete; 33 | import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; 34 | import org.apache.http.client.methods.HttpGet; 35 | import org.apache.http.client.methods.HttpPost; 36 | import org.apache.http.client.methods.HttpPut; 37 | import org.apache.http.client.methods.HttpUriRequest; 38 | import org.apache.http.conn.scheme.Scheme; 39 | import org.apache.http.conn.ssl.SSLSocketFactory; 40 | import org.apache.http.entity.ByteArrayEntity; 41 | import org.apache.http.params.HttpConnectionParams; 42 | import org.apache.http.params.HttpParams; 43 | import org.simple.net.base.Request; 44 | import org.simple.net.base.Response; 45 | import org.simple.net.config.HttpClientConfig; 46 | 47 | import java.util.Map; 48 | 49 | /** 50 | * api 9以下使用HttpClient执行网络请求, https配置参考http://jackyrong.iteye.com/blog/1606444 51 | * 52 | * @author mrsimple 53 | */ 54 | public class HttpClientStack implements HttpStack { 55 | 56 | /** 57 | * 使用HttpClient执行网络请求时的Https配置 58 | */ 59 | HttpClientConfig mConfig = HttpClientConfig.getConfig(); 60 | /** 61 | * HttpClient 62 | */ 63 | HttpClient mHttpClient = AndroidHttpClient.newInstance(mConfig.userAgent); 64 | 65 | @Override 66 | public Response performRequest(Request request) { 67 | try { 68 | HttpUriRequest httpRequest = createHttpRequest(request); 69 | // 添加连接参数 70 | setConnectionParams(httpRequest); 71 | // 添加header 72 | addHeaders(httpRequest, request.getHeaders()); 73 | // https配置 74 | configHttps(request); 75 | // 执行请求 76 | HttpResponse response = mHttpClient.execute(httpRequest); 77 | // 构建Response 78 | Response rawResponse = new Response(response.getStatusLine()); 79 | // 设置Entity 80 | rawResponse.setEntity(response.getEntity()); 81 | return rawResponse; 82 | } catch (Exception e) { 83 | } 84 | 85 | return null; 86 | } 87 | 88 | /** 89 | * 如果是https请求,则使用用户配置的SSLSocketFactory进行配置. 90 | * 91 | * @param request 92 | */ 93 | private void configHttps(Request request) { 94 | SSLSocketFactory sslSocketFactory = mConfig.getSocketFactory(); 95 | if (request.isHttps() && sslSocketFactory != null) { 96 | Scheme sch = new Scheme("https", sslSocketFactory, 443); 97 | mHttpClient.getConnectionManager().getSchemeRegistry().register(sch); 98 | } 99 | } 100 | 101 | /** 102 | * 设置连接参数,这里比较简单啊.一些优化设置就没有写了. 103 | * 104 | * @param httpUriRequest 105 | */ 106 | private void setConnectionParams(HttpUriRequest httpUriRequest) { 107 | HttpParams httpParams = httpUriRequest.getParams(); 108 | HttpConnectionParams.setConnectionTimeout(httpParams, mConfig.connTimeOut); 109 | HttpConnectionParams.setSoTimeout(httpParams, mConfig.soTimeOut); 110 | } 111 | 112 | /** 113 | * 根据请求类型创建不同的Http请求 114 | * 115 | * @param request 116 | * @return 117 | */ 118 | static HttpUriRequest createHttpRequest(Request request) { 119 | HttpUriRequest httpUriRequest = null; 120 | switch (request.getHttpMethod()) { 121 | case GET: 122 | httpUriRequest = new HttpGet(request.getUrl()); 123 | break; 124 | case DELETE: 125 | httpUriRequest = new HttpDelete(request.getUrl()); 126 | break; 127 | case POST: { 128 | httpUriRequest = new HttpPost(request.getUrl()); 129 | httpUriRequest.addHeader(Request.HEADER_CONTENT_TYPE, request.getBodyContentType()); 130 | setEntityIfNonEmptyBody((HttpPost) httpUriRequest, request); 131 | } 132 | break; 133 | case PUT: { 134 | httpUriRequest = new HttpPut(request.getUrl()); 135 | httpUriRequest.addHeader(Request.HEADER_CONTENT_TYPE, request.getBodyContentType()); 136 | setEntityIfNonEmptyBody((HttpPut) httpUriRequest, request); 137 | } 138 | break; 139 | default: 140 | throw new IllegalStateException("Unknown request method."); 141 | } 142 | 143 | return httpUriRequest; 144 | } 145 | 146 | private static void addHeaders(HttpUriRequest httpRequest, Map headers) { 147 | for (String key : headers.keySet()) { 148 | httpRequest.setHeader(key, headers.get(key)); 149 | } 150 | } 151 | 152 | /** 153 | * 将请求参数设置到HttpEntity中 154 | * 155 | * @param httpRequest 156 | * @param request 157 | */ 158 | private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest, 159 | Request request) { 160 | byte[] body = request.getBody(); 161 | if (body != null) { 162 | HttpEntity entity = new ByteArrayEntity(body); 163 | httpRequest.setEntity(entity); 164 | } 165 | } 166 | } 167 | -------------------------------------------------------------------------------- /network/SimpleNet/src/org/simple/net/httpstacks/HttpStack.java: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.simple.net.httpstacks; 26 | 27 | import org.simple.net.base.Request; 28 | import org.simple.net.base.Response; 29 | 30 | /** 31 | * 执行网络请求的接口 32 | * 33 | * @author mrsimple 34 | */ 35 | public interface HttpStack { 36 | /** 37 | * 执行Http请求 38 | * 39 | * @param request 待执行的请求 40 | * @return 41 | */ 42 | public Response performRequest(Request request); 43 | } 44 | -------------------------------------------------------------------------------- /network/SimpleNet/src/org/simple/net/httpstacks/HttpStackFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.simple.net.httpstacks; 26 | 27 | import android.os.Build; 28 | 29 | /** 30 | * 根据api版本选择HttpClient或者HttpURLConnection 31 | * 32 | * @author mrsimple 33 | */ 34 | public final class HttpStackFactory { 35 | 36 | private static final int GINGERBREAD_SDK_NUM = 9; 37 | 38 | /** 39 | * 根据SDK版本号来创建不同的Http执行器,即SDK 9之前使用HttpClient,之后则使用HttlUrlConnection, 40 | * 两者之间的差别请参考 : 41 | * http://android-developers.blogspot.com/2011/09/androids-http-clients.html 42 | * 43 | * @return 44 | */ 45 | public static HttpStack createHttpStack() { 46 | int runtimeSDKApi = Build.VERSION.SDK_INT; 47 | if (runtimeSDKApi >= GINGERBREAD_SDK_NUM) { 48 | return new HttpUrlConnStack(); 49 | } 50 | 51 | return new HttpClientStack(); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /network/SimpleNet/src/org/simple/net/httpstacks/HttpUrlConnStack.java: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.simple.net.httpstacks; 26 | 27 | import org.apache.http.Header; 28 | import org.apache.http.HttpEntity; 29 | import org.apache.http.ProtocolVersion; 30 | import org.apache.http.StatusLine; 31 | import org.apache.http.entity.BasicHttpEntity; 32 | import org.apache.http.message.BasicHeader; 33 | import org.apache.http.message.BasicHttpResponse; 34 | import org.apache.http.message.BasicStatusLine; 35 | import org.simple.net.base.Request; 36 | import org.simple.net.base.Request.HttpMethod; 37 | import org.simple.net.base.Response; 38 | import org.simple.net.config.HttpUrlConnConfig; 39 | 40 | import java.io.DataOutputStream; 41 | import java.io.IOException; 42 | import java.io.InputStream; 43 | import java.net.HttpURLConnection; 44 | import java.net.ProtocolException; 45 | import java.net.URL; 46 | import java.net.URLConnection; 47 | import java.util.List; 48 | import java.util.Map.Entry; 49 | import java.util.Set; 50 | 51 | import javax.net.ssl.HttpsURLConnection; 52 | import javax.net.ssl.SSLSocketFactory; 53 | 54 | /** 55 | * 使用HttpURLConnection执行网络请求的HttpStack 56 | * 57 | * @author mrsimple 58 | */ 59 | public class HttpUrlConnStack implements HttpStack { 60 | 61 | /** 62 | * 配置Https 63 | */ 64 | HttpUrlConnConfig mConfig = HttpUrlConnConfig.getConfig(); 65 | 66 | @Override 67 | public Response performRequest(Request request) { 68 | HttpURLConnection urlConnection = null; 69 | try { 70 | // 构建HttpURLConnection 71 | urlConnection = createUrlConnection(request.getUrl()); 72 | // 设置headers 73 | setRequestHeaders(urlConnection, request); 74 | // 设置Body参数 75 | setRequestParams(urlConnection, request); 76 | // https 配置 77 | configHttps(request); 78 | return fetchResponse(urlConnection); 79 | } catch (Exception e) { 80 | e.printStackTrace(); 81 | } finally { 82 | if (urlConnection != null) { 83 | urlConnection.disconnect(); 84 | } 85 | } 86 | return null; 87 | } 88 | 89 | private HttpURLConnection createUrlConnection(String url) throws IOException { 90 | URL newURL = new URL(url); 91 | URLConnection urlConnection = newURL.openConnection(); 92 | urlConnection.setConnectTimeout(mConfig.connTimeOut); 93 | urlConnection.setReadTimeout(mConfig.soTimeOut); 94 | urlConnection.setDoInput(true); 95 | urlConnection.setUseCaches(false); 96 | return (HttpURLConnection) urlConnection; 97 | } 98 | 99 | private void configHttps(Request request) { 100 | if (request.isHttps()) { 101 | SSLSocketFactory sslFactory = mConfig.getSslSocketFactory(); 102 | // 配置https 103 | if (sslFactory != null) { 104 | HttpsURLConnection.setDefaultSSLSocketFactory(sslFactory); 105 | HttpsURLConnection.setDefaultHostnameVerifier(mConfig.getHostnameVerifier()); 106 | } 107 | 108 | } 109 | } 110 | 111 | private void setRequestHeaders(HttpURLConnection connection, Request request) { 112 | Set headersKeys = request.getHeaders().keySet(); 113 | for (String headerName : headersKeys) { 114 | connection.addRequestProperty(headerName, request.getHeaders().get(headerName)); 115 | } 116 | } 117 | 118 | protected void setRequestParams(HttpURLConnection connection, Request request) 119 | throws ProtocolException, IOException { 120 | HttpMethod method = request.getHttpMethod(); 121 | connection.setRequestMethod(method.toString()); 122 | // add params 123 | byte[] body = request.getBody(); 124 | if (body != null) { 125 | // enable output 126 | connection.setDoOutput(true); 127 | // set content type 128 | connection 129 | .addRequestProperty(Request.HEADER_CONTENT_TYPE, request.getBodyContentType()); 130 | // write params data to connection 131 | DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream()); 132 | dataOutputStream.write(body); 133 | dataOutputStream.close(); 134 | } 135 | } 136 | 137 | private Response fetchResponse(HttpURLConnection connection) throws IOException { 138 | 139 | // Initialize HttpResponse with data from the HttpURLConnection. 140 | ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); 141 | int responseCode = connection.getResponseCode(); 142 | if (responseCode == -1) { 143 | throw new IOException("Could not retrieve response code from HttpUrlConnection."); 144 | } 145 | // 状态行数据 146 | StatusLine responseStatus = new BasicStatusLine(protocolVersion, 147 | connection.getResponseCode(), connection.getResponseMessage()); 148 | // 构建response 149 | Response response = new Response(responseStatus); 150 | // 设置response数据 151 | response.setEntity(entityFromURLConnwction(connection)); 152 | addHeadersToResponse(response, connection); 153 | return response; 154 | } 155 | 156 | /** 157 | * 执行HTTP请求之后获取到其数据流,即返回请求结果的流 158 | * 159 | * @param connection 160 | * @return 161 | */ 162 | private HttpEntity entityFromURLConnwction(HttpURLConnection connection) { 163 | BasicHttpEntity entity = new BasicHttpEntity(); 164 | InputStream inputStream = null; 165 | try { 166 | inputStream = connection.getInputStream(); 167 | } catch (IOException e) { 168 | e.printStackTrace(); 169 | inputStream = connection.getErrorStream(); 170 | } 171 | 172 | // TODO : GZIP 173 | entity.setContent(inputStream); 174 | entity.setContentLength(connection.getContentLength()); 175 | entity.setContentEncoding(connection.getContentEncoding()); 176 | entity.setContentType(connection.getContentType()); 177 | 178 | return entity; 179 | } 180 | 181 | private void addHeadersToResponse(BasicHttpResponse response, HttpURLConnection connection) { 182 | for (Entry> header : connection.getHeaderFields().entrySet()) { 183 | if (header.getKey() != null) { 184 | Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); 185 | response.addHeader(h); 186 | } 187 | } 188 | } 189 | 190 | } 191 | -------------------------------------------------------------------------------- /network/SimpleNet/src/org/simple/net/requests/JsonRequest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.simple.net.requests; 26 | 27 | import org.json.JSONException; 28 | import org.json.JSONObject; 29 | import org.simple.net.base.Request; 30 | import org.simple.net.base.Response; 31 | 32 | /** 33 | * 返回的数据类型为Json的请求, Json对应的对象类型为JSONObject 34 | * 35 | * @author mrsimple 36 | */ 37 | public class JsonRequest extends Request { 38 | 39 | public JsonRequest(HttpMethod method, String url, RequestListener listener) { 40 | super(method, url, listener); 41 | } 42 | 43 | 44 | /** 45 | * 将Response的结果转换为JSONObject 46 | */ 47 | @Override 48 | public JSONObject parseResponse(Response response) { 49 | String jsonString = new String(response.getRawData()); 50 | try { 51 | return new JSONObject(jsonString); 52 | } catch (JSONException e) { 53 | e.printStackTrace(); 54 | } 55 | return null; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /network/SimpleNet/src/org/simple/net/requests/MultipartRequest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.simple.net.requests; 26 | 27 | import android.util.Log; 28 | 29 | import org.simple.net.base.Request; 30 | import org.simple.net.base.Response; 31 | import org.simple.net.entity.MultipartEntity; 32 | 33 | import java.io.ByteArrayOutputStream; 34 | import java.io.IOException; 35 | 36 | /** 37 | * Multipart请求 ( 只能为POST请求 ),该请求可以搭载多种类型参数,比如文本、文件等,但是文件仅限于小文件,否则会出现OOM异常. 38 | * 39 | * @author mrsimple 40 | */ 41 | public class MultipartRequest extends Request { 42 | 43 | MultipartEntity mMultiPartEntity = new MultipartEntity(); 44 | 45 | public MultipartRequest(String url, RequestListener listener) { 46 | super(HttpMethod.POST, url, listener); 47 | } 48 | 49 | /** 50 | * @return 51 | */ 52 | public MultipartEntity getMultiPartEntity() { 53 | return mMultiPartEntity; 54 | } 55 | 56 | @Override 57 | public String getBodyContentType() { 58 | return mMultiPartEntity.getContentType().getValue(); 59 | } 60 | 61 | @Override 62 | public byte[] getBody() { 63 | ByteArrayOutputStream bos = new ByteArrayOutputStream(); 64 | try { 65 | // 将MultipartEntity中的参数写入到bos中 66 | mMultiPartEntity.writeTo(bos); 67 | } catch (IOException e) { 68 | Log.e("", "IOException writing to ByteArrayOutputStream"); 69 | } 70 | return bos.toByteArray(); 71 | } 72 | 73 | @Override 74 | public String parseResponse(Response response) { 75 | if (response != null && response.getRawData() != null) { 76 | return new String(response.getRawData()); 77 | } 78 | 79 | return ""; 80 | } 81 | 82 | } 83 | -------------------------------------------------------------------------------- /network/SimpleNet/src/org/simple/net/requests/StringRequest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package org.simple.net.requests; 26 | 27 | import org.simple.net.base.Request; 28 | import org.simple.net.base.Response; 29 | 30 | public class StringRequest extends Request { 31 | 32 | public StringRequest(HttpMethod method, String url, RequestListener listener) { 33 | super(method, url, listener); 34 | } 35 | 36 | @Override 37 | public String parseResponse(Response response) { 38 | return new String(response.getRawData()); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /orm/README.md: -------------------------------------------------------------------------------- 1 | # 任务表 2 | | 开源框架名称 | 作者 | 预计完成时间 | 3 | | ------------- |:-------------:| ------------- | 4 | | | [用户名](git地址) | 完成时间 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /others/README.md: -------------------------------------------------------------------------------- 1 | # 任务表 2 | | 简版框架名称 | 作者 | 预计完成时间 | 3 | | ------------- |:-------------:| ------------- | 4 | | 这里指向你的框架文件夹 | [用户名](git地址) | 完成时间 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /template.md: -------------------------------------------------------------------------------- 1 | ${简版开源库} 的设计与实现 2 | ==================================== 3 | > 本文为 [Android著名开源库的简版实现](https://github.com/simple-android-framework-exchange/simple-android-opensource-framework) 中的 ${简版开源库} 的设计与实现 4 | > 原始开源库: [${原始开源库名称}](链接) 5 | > 作者:[作者用户名](作者github链接),开发状态:完成/未完成,校对者:[等待管理员填写](),校对状态:未开始 6 | 7 | 8 | 建议大家看下 [SimpleNet](network/SimpleNet/README.md),了解应该写到什么程度,以及类似流程图和总体设计该怎么做。当然,如果你只想写README.md一篇介绍,那么该文档中必须包含详细的设计与源码实现介绍,阐述其核心原理。如果你的README.md只是一篇介绍性文档,那么后续必须增加其他阐述核心原理的其他文档。 9 | 10 | `复制一份到自己的项目文件夹下,然后根据自己项目替换掉 ${} 内容,删掉本行及上面两行。` 11 | 12 | ## 1. 功能介绍 13 | 功能介绍,包括功能或优点等 14 | 15 | 16 | ## 2. 总体设计 17 | 整个库分为哪些模块及模块之间的调用关系。 18 | - 如大多数图片缓存会分为 Loader 和 Processer 等模块。 19 | - 可使用 [Google Drawing](https://docs.google.com/drawings)、[Visio](http://products.office.com/en-us/visio/flowchart-software)、[StarUML](http://staruml.io/) 等工具完成,其他工具推荐?? 20 | - 非所有项目必须,不需要的请先在群里反馈。 21 | 22 | 23 | ## 3. 流程图 24 | 主要功能流程图 25 | 26 | - 如 Retrofit、Volley 的请求处理流程,Android-Universal-Image-Loader 的图片处理流程图 27 | - 可使用 [Google Drawing](https://docs.google.com/drawings)、[Visio](http://products.office.com/en-us/visio/flowchart-software)、[StarUML](http://staruml.io/) 等工具完成,其他工具推荐?? 28 | - 非所有项目必须,不需要的请先在群里反馈 29 | 30 | 31 | 32 | 33 | ## 4. 详细设计 34 | ### 4.1 核心类详细介绍 35 | 36 | 类及其主要函数功能介绍、核心功能流程图,流程图可使用 [Google Drawing](https://docs.google.com/drawings)、[Visio](http://products.office.com/en-us/visio/flowchart-software)、[StarUML](http://staruml.io/)。 37 | 38 | 39 | ### 4.2 类关系图 40 | 类关系图,类的继承、组合关系图,可是用 [StarUML](http://staruml.io/) 工具。 41 | 42 | 43 | 44 | 45 | ##5. 杂谈 46 | 该项目存在的问题、可优化点及类似功能项目对比等,非所有项目必须。 47 | 48 | 49 | 50 | 51 | `写完相关内容之后到开发群告知管理员,管理员安排相关人员进行审核,审核通过之后即可。` 52 | 53 | -------------------------------------------------------------------------------- /view/README.md: -------------------------------------------------------------------------------- 1 | # 任务表 2 | | 简版框架名称 | 作者 | 预计完成时间 | 3 | | ------------- |:-------------:| ------------- | 4 | | 这里指向你的框架文件夹 | [用户名](git地址) | 完成时间 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | --------------------------------------------------------------------------------