Volley-demo
===========
An demonstration of Volley - HTTP library announced by google in I/O 2013.
## Play Store Link for demo download
https://play.google.com/store/apps/details?id=com.mani.volleydemo
## Why Volley?
Android has provided two HTTP Clients *AndroidHttpClient* (Extended from apache HTTPClient) and *HttpUrlConnection*
to make a HTTP Request. Both has its own pros and cons. When an application is developed, we write HTTP connection classes which handles
all the HTTP requests, creating THREADS to run in background, managing THREAD pool, response parsing, response caching, handling error codes, SSL connections, running requests in parallel and others stuffs around that.
Every developer has his own way of implementing these functionalities.Some might use AsycnTask for running network operations in background, or some might use passing handlers created from UI thread to HTTP connection classes which then executes network operation in worker thread and uses the handler to pass back the parsed HTTP response back to the main thread.
But we end up writing same boilerplate codes repeatedly and we try to reinvent the wheel in our application development.
For example, in the below snippet, a HTTP request is made in the AysncTask's *doBackground* method. When the response is obtained,
data is copied from HttpUrlConnection's *InputStream* to *OutputStream* and then it tries to convert the string obtained from
outputStream to *JSONObject* which is our final response. On the course, all the necessary try, catch block is handled.
All these boilerplate codes are repeated throughout our code.
```
HttpURLConnection urlConnection = null;
try {
URL url = new URL("http://www.android.com/");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024]; // Adjust if you want
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
JSONObject resultJSON = new JSONObject(outputStream.toString());
}catch (Exception e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
```
Google has come up with Volley interface which helps developers to handle all the network related operations so that developers can concentrate
implementing the business logic after the HTTP response is obtained.Also having less code for network calls helps developer reduce number of bugs.
*NOTE* Volley is not good for larger file download/upload operations as well video streaming operations.
Key features of the Volley are below
* Develop Super fast networked applications for android.
* Schedules all your HTTP requests running them parallely in background threads and manages those threads.
* Gives you flexible ways to run your networking requests concurrently with synchronization.
* Comes with inbuilt JSON parsing the response.
* Set prioirty for requests.
* Retry policy for timeout,certain ERROR codes as Internal Server error.
* Flexible Request cancellations.
* Memory & Disk Caching for images.Batch dispatch to Image Downloads.
* Flexible in giving your own cache implementations.
* You can include your own HTTPStack ( to handle SSL connections, PATCH requests ).
* Effective inbuilt cache - control to handle response caching.
* Request tracing for debugging.
* Excels in the way responses are given back to you.
## Integrating Volley to your project.
You can include in two ways
* Create *Volley.jar* and include as *jar dependency* to your project.
* Include the volley project as *Library Dependency* in your project.
Clone the Volley project from below git repo.
https://android.googlesource.com/platform/frameworks/volley/)
1. Creating Volley.jar
* Import the project into eclipse.
* $ cd volley
* $ android update project -p . (Generate local.properties file )
* $ ant jar
* Right click on build.xml file and ‘Run as Ant Task’ , volley.jar would be created in /bin folder.
2. Library Dependency
* Edit the project.properties file and the add the below line
* android.library=true
* Now right click on your project--> Properties--> Android --> Under Library section, choose ‘Add’ and select ‘Volley’ project as library dependency to your project.
Using Volley involves two main classes **RequestQueue** and **Request**.
* RequestQueue - Dispatch Queue which takes a Request and executes in a worker thread or if cache found its takes from cache and responds back to the UI main thread.
* Request - All network(HTTP) requests are created from this class. It takes main parameters required for a HTTP request like
* METHOD Type - GET, POST, PUT, DELETE
* URL
* Request data (HTTP Body)
* Successful Response Listener
* Error Listener
Volley Provides two specific implementations of **Request**.
* JsonObjectRequest
* StringRequest
## Initialise RequestQueue
```
mVolleyQueue = Volley.newRequestQueue(this);
```
You can create a instance of RequestQueue by passing any *Object* to the static method *newRequestQueue* of Volley Class.
In this case, activity instance *this* is passed to create the instance. Similarly while cancelling all the requests dispatched
in this RequestQueue we should be using activity instance to cancel the requests.
## JsonObjectRequest
Creates HTTP request which helps in connecting to JSON based response API's. Takes parameters as
* HTTP METHOD
* A JSON object as request body ( mostly for POST & PUT api's)
* Success & Error Listener.
Volley parses the HTTP Response to a JSONObject for you. If your server api's are JSON based, you can straightway go ahead and use *JsonObjectRequest*
> The **Content-Type** for this request is always set to *application/json*
```
String url = "<SERVER_API>";
JsonObjectRequest jsonObjRequest = new JsonObjectRequest(Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
mVolleyQueue.add(jsonObjRequest);
```
## StringRequest
To obtain the HTTP Response as a String, create HTTP Request using *StringRequest*
Takes parameters as
* HTTP METHOD
* Success & Error Listener.
```
String url = "<SERVER-API>";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
mVolleyQueue.add(stringRequest);
```
## GsonRequest
You can customize the *Request<T>* to make a new type of Request which can give the response in Java Class Object.
GSON is a library which is used in converting JSON to Java Class Objects and vice-versa. You write custom request which takes Java Class name as a parameter and return the response in that Class Object.
You should include **gson.jar** as JAR dependency in your project.
```
public class GsonRequest<T> extends Request<T>{
private Gson mGson;
public GsonRequest(int method, String url, Class<T> cls, String requestBody, Listener<T> listener,
ErrorListener errorListener) {
super(method, url, errorListener);
mGson = new Gson();
}
@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
T parsedGSON = mGson.fromJson(jsonString, mJavaClass);
return Response.success(parsedGSON,
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException je) {
return Response.error(
没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
收起资源包目录
volley框架封装(实现的非常好) (101个子文件)
.gitignore.bak 56B
production_test_ca.bks 759B
.classpath 510B
.gitignore 34B
httpclient-4.2.5.jar 423KB
android-support-v4.jar 384KB
gson-2.2.2.jar 185KB
httpmime-4.2.5.jar 26KB
ImageLoader.java 19KB
Request.java 18KB
DiskBasedCache.java 17KB
NetworkImageActivity.java 13KB
JSONObjectRequestActvity.java 11KB
RequestQueue.java 10KB
BasicNetwork.java 10KB
GSONObjectRequestActivity.java 9KB
HurlStack.java 9KB
SslHttpStack.java 9KB
ImageRequest.java 8KB
EasySSLSocketFactory.java 8KB
NetworkImageView.java 8KB
HttpClientStack.java 7KB
R.java 6KB
VolleyLog.java 6KB
CacheDispatcher.java 6KB
StringObjectRequestActivity.java 6KB
NetworkDispatcher.java 5KB
ByteArrayPool.java 5KB
HttpHeaderParser.java 5KB
MultiPartRequest.java 4KB
MainActivity.java 4KB
RequestFuture.java 4KB
ExecutorDelivery.java 4KB
SSLConnectionActivity.java 4KB
AndroidAuthenticator.java 4KB
GsonRequest.java 3KB
JsonRequest.java 3KB
Volley.java 3KB
JsonObjectRequest.java 3KB
EasyX509TrustManager.java 3KB
PoolingByteArrayOutputStream.java 3KB
DefaultRetryPolicy.java 3KB
Cache.java 3KB
Response.java 3KB
StringRequest.java 2KB
MyJsonRequest.java 2KB
JsonArrayRequest.java 2KB
ClearCacheRequest.java 2KB
NetworkResponse.java 2KB
FadeInImageListener.java 2KB
MyStringRequest.java 2KB
BitmapLruCache.java 2KB
AuthFailureError.java 2KB
HttpStack.java 1KB
BitmapUtil.java 1KB
VolleyError.java 1KB
RetryPolicy.java 1KB
ResponseDelivery.java 1KB
NoCache.java 1KB
NetworkError.java 1KB
Authenticator.java 1KB
ParseError.java 1KB
Network.java 1KB
ServerError.java 1KB
NoConnectionError.java 971B
FlickrImage.java 827B
TimeoutError.java 794B
IgnoreCertTrustManager.java 592B
VolleySampleApplication.java 392B
FlickrResponsePhotos.java 237B
FlickrResponse.java 200B
BuildConfig.java 161B
README.md 25KB
production_test_client.p12 2KB
ic_launcher.png 24KB
ic_launcher.png 12KB
ic_launcher.png 7KB
ic_launcher.png 4KB
flickr.png 3KB
org.eclipse.jdt.core.prefs 173B
org.eclipse.core.resources.prefs 55B
.project 813B
project.properties 563B
proguard-project.txt 781B
main_layout.xml 3KB
networkimage_layout.xml 2KB
AndroidManifest.xml 2KB
colors.xml 1KB
dimens.xml 1KB
json_object_layout.xml 974B
string_object_layout.xml 916B
networkimage_list_item.xml 846B
list_item.xml 812B
styles.xml 679B
styles.xml 380B
styles.xml 323B
fade_in.xml 281B
dimens.xml 268B
main.xml 205B
dimens.xml 195B
共 101 条
- 1
- 2
资源评论
- 劇終男爵2016-06-01不错 很好用
qq_31198807
- 粉丝: 2
- 资源: 50
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功