> android Volley 上传文件上传图片:http://blog.csdn.net/com314159/article/details/39853865
GitHub:https://github.com/com314159/VolleyMultiPartRequest
> Android volley 解析(三)之文件上传篇: http://blog.csdn.net/jxxfzgy/article/details/44064481
http://www.2cto.com/kf/201412/365803.html
----------------------------------------------------------------------------------------------
引用:http://www.open-open.com/lib/view/open1407727047207.html
> 首先简单描述一下Google的Android开发团队在2013年推出的一个网络通信框架Volley.它的设计目标是进行数据量不大,但通信频繁的网络操作,而对于大数据量的网络操作,比如下载文件等,Volley的表现就不尽如人意。
在app开发中,我们最常见的就是从app客户端向服务端发一个http请求.对于两种基本的web请求方式get和post来说,get请求方式相对比较简单,在此略过不表.本文重点描述一下通过volley进行几种post提交的方式.
1.客户端以普通的post方式进行提交,服务端返回字符串
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(Request.Method.POST,httpurl,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "response -> " + response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, error.getMessage(), error);
}
}) {
@Override
protected Map<String, String> getParams() {
//在这里设置需要post的参数
Map<String, String> map = new HashMap<String, String>();
map.put("name1", "value1");
map.put("name2", "value2");
return params;
}
requestQueue.add(stringRequest);
2.客户端以json串的post请求方式进行提交,服务端返回json串
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
Map<String, String> map = new HashMap<String, String>();
map.put("name1", "value1");
map.put("name2", "value2");
JSONObject jsonObject = new JSONObject(params);
JsonRequest<JSONObject> jsonRequest = new JsonObjectRequest(Method.POST,httpurl, jsonObject,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, "response -> " + response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, error.getMessage(), error);
}
})
{
//注意此处override的getParams()方法,在此处设置post需要提交的参数根本不起作用
//必须象上面那样,构成JSONObject当做实参传入JsonObjectRequest对象里
//所以这个方法在此处是不需要的
//post提交请求参数
// @Override
// protected Map<String, String> getParams() {
// Map<String, String> map = new HashMap<String, String>();
// map.put("name1", "value1");
// map.put("name2", "value2");
// return params;
// }
//post提交请求头
@Override
public Map<String, String> getHeaders() {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json");
headers.put("Content-Type", "application/json; charset=UTF-8");
return headers;
}
};
requestQueue.add(jsonRequest);
看了上面这段代码,会觉得volley这个框架实在是还不够完善,使用JsonObjectRequest对象提交一个post请求,如果有参数需要提交,就必须以JSONObject的json串方式提交.
如果服务端并不支持这种方式呢?比如常见的spring mvc服务端,就很难支持json的请求方式.
那么我们想实现这个目标,就需要使用下面给出的办法.
3.客户端以普通的post方式进行提交,服务端返回json串。首先在Activity类里,继承Request实现一个NormalPostRequest类
private class NormalPostRequest extends Request<JSONObject> {
private Map<String, String> mMap;
private Listener<JSONObject> mListener;
public NormalPostRequest(String url, Listener<JSONObject> listener,ErrorListener errorListener, Map<String, String> map) {
super(Request.Method.POST, url, errorListener);
mListener = listener;
mMap = map;
}
//mMap是已经按照前面的方式,设置了参数的实例
@Override
protected Map<String, String> getParams() throws AuthFailureError {
return mMap;
}
//此处因为response返回值需要json数据,和JsonObjectRequest类一样即可
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
@Override
protected void deliverResponse(JSONObject response) {
mListener.onResponse(response);
}
}
接下来的调用方式和前面差不多,生成一个Request实例,加入队列中即可.
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
Request<JSONObject> request = new NormalPostRequest(httpurl,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, "response -> " + response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, error.getMessage(), error);
}
}, params);
requestQueue.add(request);
---------------------------------------------------------------------------------------------
》Android Volley Https证书不信任的解决方案:(单向认证)
首先新建一个类FakeX509TrustManager:
public class FakeX509TrustManager implements X509TrustManager {
private static TrustManager[] trustManagers;
private static final X509Certificate[] _AcceptedIssuers = new
X509Certificate[] {};
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException {
//To change body of implemented methods use File | Settings | File Templates.
}
public boolean isClientTrusted(X509Certificate[] chain) {
return true;
}
public boolean isServerTrusted(X509Certificate[] chain) {
return true;
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return _AcceptedIssuers;
}
public static void allowAllSSL() {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
// TODO Auto-generated method stub
return true;
}
});
SSLContext context = null;
if (trustManagers == null) {
trustManagers = new TrustManager[] { new FakeX509TrustManager() };
}
try {
context = SSLContext.getInstance("TLS");
context.init(null, trustManagers, new SecureRandom());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
}
}
然后在进行StringRequest之前设置:
FakeX509TrustManager.allowAllSSL();
mStringRequest = new StringRequest(Request.Method.POST,
url,
getDefaultSuccessListener(),
mErrorListener){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
return params;
}
};
mRequestQueue.add(mStringRequest);
------------------------------------------------------------------
》取消Request
Activity里面启动了网络请求,而在这个网络请求还没返回结果的时候,Activity被结束了,此时如果继续使用其中的Context等,除了无辜的浪费CPU,电池,网络等资源,有可能还会导致程序crash,所以,我们需要处理这种一场情况。使用Volley的话,我们可以在Activity停止的时候,同时取消所有或部分未完成的网络请求。Volley里所有的请求结果会返回给主进程,如果在主进程里取消了某些请求,则这些请求将不会被返回给主线程。Volley支持多种request取消方式。
1)可以针对某些个request做取消操作:
@Override public void onStop() { for (Request <?> req : mRequestQueue) { req.cancel(); } }
2)取消这个队列里的所有请求:
@Override protected void onStop() { // TODO Auto-generated method stub super.onStop(); mRequestQueue.cancelAll(this); }
3)可以根据RequestFilter或者Tag来终止某些请求
@Override protected void onStop() { // TODO Auto-generated method stub super.onStop(); mRequestQueue.cancelAll( new RequestFilter() {}); or mRequestQueue.cancelAll(new Object()); }
Volley支持http的GET、POST、PUT、DELETE等方法。