JSON,图像等的异步下载
网络请求的排序(scheduling)
网络请求的优先级处理
缓存
多级别取消请求
和Activity和生命周期的联动(Activity结束时同时取消所有网络请求)
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();
}
JsonObjectRequest
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
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
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(new ParseError(je));
}
}
}
图片的下载
SSL connections
SslHttpStack implements HtpStack
@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
throws IOException, AuthFailureError {
HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders);
-----------------------
-----------------------
/* Register schemes, HTTP and HTTPS */
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", new PlainSocketFactory(), 80));
registry.register(new Scheme("https", new EasySSLSocketFactory(mIsConnectingToYourServer), 443));
/* Make a thread safe connection manager for the client */
ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(httpParams, registry);
HttpClient httpClient = new DefaultHttpClient(manager, httpParams);
}
多部分 发送请求
public class MultiPartRequest extends JsonRequest<JSONObject> {
/* To hold the parameter name and the File to upload */
private Map<String,File> fileUploads = new HashMap<String,File>();
/* To hold the parameter name and the string content to upload */
private Map<String,String> stringUploads = new HashMap<String,String>();
public void addFileUpload(String param,File file) {
fileUploads.put(param,file);
}
public void addStringUpload(String param,String content) {
stringUploads.put(param,content);
}
public Map<String,File> getFileUploads() {
return fileUploads;
}
public Map<String,String> getStringUploads() {
return stringUploads;
}
}
private static void setMultiPartBody(HttpEntityEnclosingRequestBase httpRequest,
Request<?> request) throws AuthFailureError {
// Return if Request is not MultiPartRequest
if(request instanceof MultiPartRequest == false) {
return;
}
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
//Iterate the fileUploads
Map<String,File> fileUpload = ((MultiPartRequest)request).getFileUploads();
for (Map.Entry<String, File> entry : fileUpload.entrySet()) {
multipartEntity.addPart(((String)entry.getKey()), new FileBody((File)entry.getValue()));
}
//Iterate the stringUploads
Map<String,String> stringUpload = ((MultiPartRequest)request).getStringUploads();
for (Map.Entry<String, String> entry : stringUpload.entrySet()) {
try {
multipartEntity.addPart(((String)entry.getKey()), new StringBody((String)entry.getValue()));
} catch (Exception e) {
e.printStackTrace();
}
}
httpRequest.setEntity(multipartEntity);
}
增加
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
public class MyStringRequest extends StringRequest{
private Map<String, String> headers = new HashMap<String, String>();
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers;
}
public void setHeader(String title, String content) {
headers.put(title, content);
}
}
处理错误的编码
@Override
public void onErrorResponse(VolleyError error) {
// Handle your error types accordingly.For Timeout & No connection error, you can show 'retry' button.
// For AuthFailure, you can re login with user credentials.
// For ClientError, 400 & 401, Errors happening on client side when sending api request.
// In this case you can check how client is forming the api and debug accordingly.
// For ServerError 5xx, you can do retry or handle accordingly.
if( error instanceof NetworkError) {
} else if( error instanceof ClientError) {
} else if( error instanceof ServerError) {
} else if( error instanceof AuthFailureError) {
} else if( error instanceof ParseError) {
} else if( error instanceof NoConnectionError) {
} else if( error instanceof TimeoutError) {
}
}
@Override
public void onErrorResponse(VolleyError error) {
hideProgressDialog();
if(error instanceof AuthFailureError) {
showAlertError(ResourcesUtil.getString(R.string.login_error_invalid_credentials));
}else if(error instanceof ClientError) {
// Convert byte to String.
String str = null;
try {
str = new String(error.networkResponse.data, "UTF8");
JSONObject errorJson = new JSONObject(str);
if( errorJson.has(Constants.ERROR)) {
JSONObject err = errorJson.getJSONObject(Constants.ERROR);
if(err.has(Constants.ERROR_MESSAGE)) {
String errorMsg = errorJson.has(Constants.ERROR_MESSAGE);
showAlertError(errorMsg);
}
return;
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
MessageUtil.showMessage(ResourcesUtil.getString(R.string.error_service), true);
}
}
取消请求
request.cancel();
( or )
for( Request<T> req : mRequestList) {
req.cancel();
}
( or )
volleyQueue.cancelAll(Object);
优先请求集合
Priority priority;
public void setPriority(Priority priority) {
this.priority = priority;
}
/*
* If prioirty set use it,else returned NORMAL
* @see com.android.volley.Request#getPriority()
*/
public Priority getPriority() {
if( this.priority != null) {
return priority;
} else {
return Priority.NORMAL;
}
}