Android-网络通信框架Volley使用详解

1 Volley发送get请求:

public void getJson() {
	String url = "http://"+host+":8080/web/json.jsp?username=xjs&password=123456";
	mQueue.add(new JsonObjectRequest(Method.GET, url, null,
		new Listener<JSONObject>() {
			@Override
			public void onResponse(JSONObject response) {
				Log.e(TAG, "response : " + response.toString());
			}
		}, new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				String err = error.getMessage();
				Log.e(TAG, "err : " + err);
			}
		}));
}

2 Volley发送post请求:

public void postJson() {
	String url = "http://"+host+":8080/web/json.jsp";
	StringRequest postRequest = new StringRequest(
			Request.Method.POST, 
			url,
			new Response.Listener<String>() {
				@Override
				public void onResponse(String response) {
					// response
					Log.d("Response", response);
				}
			}, new Response.ErrorListener() {
				@Override
				public void onErrorResponse(VolleyError error) {
					// error
					Log.d("Error.Response", error.getMessage());
				}
			}) {
		@Override
		protected Map<String, String> getParams() {
			Map<String, String> params = new HashMap<String, String>();
			params.put("username", "xjs");
			params.put("password", "123456");
			return params;
		}
	};
	mQueue.add(postRequest);
}

3 Volley获取网络图片:

public void getImage() {
	String imageUrl = "http://"+host+":8080/web/image.jsp";
	NetworkImageView view = (NetworkImageView) findViewById(R.id.network_image_view);
	view.setDefaultImageResId(android.R.drawable.ic_menu_rotate); 
	view.setErrorImageResId(android.R.drawable.ic_delete); 
	view.setImageUrl(imageUrl, new ImageLoader(mQueue, new BitmapLruCache(1024 * 4)));
}

4 Volley发送Https请求,需要修改源码:

protected HttpURLConnection createConnection(URL url) throws IOException {
	if (url.toString().toLowerCase(Locale.CHINA).startsWith("https")) {
		HTTPSTrustManager.allowAllSSL();
	}
	return (HttpURLConnection) url.openConnection();
}
//HTTPSTrustManager.java:
public class HTTPSTrustManager 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 HTTPSTrustManager() };
		}
		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());
	}
}

5 Volley获取服务端返回的cookie,需要修改源码:

@Override
public HttpResponse performRequest(Request<?> request,Map<String, String> additionalHeaders) 
	throws IOException,AuthFailureError {
	for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
	if (header.getKey() != null) {
		String key = header.getKey();
		List<String> values = header.getValue();
		if(key.equalsIgnoreCase("set-cookie")){
			StringBuilder cookieString = new StringBuilder();
			for(String value : values){
				cookieString.append(value).append("\n");//用\n作为分隔符,cookie中不应该有回车符号
			}
			cookieString.deleteCharAt(cookieString.length() - 1);
			Header h = new BasicHeader(header.getKey(), cookieString.toString());
			response.addHeader(h);
		}else{
			Header h = new BasicHeader(header.getKey(), values.get(0));
			response.addHeader(h);
		}
	}
}
}
//然后再request中重写parseNetworkResponse():
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
	Response<String> superResponse = super.parseNetworkResponse(response);
	Map<String, String> responseHeaders = response.headers;
	String rawCookies = responseHeaders.get("Set-Cookie");
	//服务端返回是 set-cookie:JSESSIONID=D90B58454550B4D37C4B66A76BF27B93; Path=/otn BIGipServerotn=2564030730.64545.0000; path=/
	String part1 = substring(rawCookies, "", ";");
	String part2 = substring(rawCookies, "\n", ";");
	//客户端需要的是 cookie:JSESSIONID=D90B58454550B4D37C4B66A76BF27B93; BIGipServerotn=2564030730.64545.0000;
	cookies = part1 + "; " + part2 + ";";
	return superResponse;
}

6 Volley发请求的时候上传cookie,在request中重写getHeaders():

@Override
public Map<String, String>getHeaders() throws AuthFailureError {
         if(cookies!= null && cookies.length() > 0){
                   HashMap<String,String>         headers = newHashMap<String, String>();
                   headers.put("Cookie",cookies);
                   returnheaders;
         }
         returnsuper.getHeaders();
}

7 Volley自定义request:

public class ByteArrayRequest extends Request<byte[]>{
	private final Listener<byte[]> mListener;
	public ByteArrayRequest(int method, String url, Listener<byte[]> listener, ErrorListener errlistener) {
		super(method, url, errlistener);
		mListener = listener;
	}
	@Override
	protected Response<byte[]> parseNetworkResponse(NetworkResponse response) {
		if(response == null){
			return null;
		}
		if(response.statusCode != HttpStatus.SC_OK){
			return null;
		}
		byte[] bytes = response.data;
		return Response.success(bytes, null);
	}
	@Override
	protected void deliverResponse(byte[] response) {
		if(mListener != null){
			mListener.onResponse(response);
		}
	}
}

8 Volley设置请求超时时间:

@Override
public RetryPolicy getRetryPolicy() { 
         RetryPolicyretryPolicy = new DefaultRetryPolicy(5000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT); 
         returnretryPolicy; 
}

附一个登陆铁道部12306的例子,源码在:http://download.csdn.net/download/goldenfish1919/7029907

Ps:我在测试的时候用了本地的一个tomcat,一块打包放在了asserts下面。

参考:

http://blog.csdn.net/xyz_lmn/article/details/12165391

http://blog.csdn.net/xyz_lmn/article/details/12746581

http://blog.csdn.net/xyz_lmn/article/details/12177005

http://www.itsalif.info/content/android-volley-tutorial-http-get-post-put

概述:http://blog.csdn.net/t12x3456/article/details/9221611

入门: http://blog.csdn.net/ttdevs/article/details/17566795

自定义request: http://blog.csdn.net/ttdevs/article/details/17586205

源码分析:http://blog.csdn.net/ttdevs/article/details/17764351

发送https请求:http://blog.csdn.net/llwdslal/article/details/18052723

构造cache:http://*.com/questions/16682595/android-volley-imageloader-bitmaplrucache-parameter

解析服务端cookie:http://*.com/questions/20702178/android-volley-access-http-response-header-fields,http://blog.csdn.net/hpb21/article/details/12163371

上传cookie:http://*.com/questions/17049473/how-to-set-custom-header-in-volley-request

设置超时:http://*.com/questions/17094718/android-volley-timeout

http://blog.csdn.net/dacainiao007/article/details/12617747,这里关于超时时间增长的因子的说法不准确,应该是当第一次连接超时以后,第二次超时时间会变为原来的多少倍,连接超时和读取超时设置为同一个数。


Android-网络通信框架Volley使用详解,布布扣,bubuko.com

Android-网络通信框架Volley使用详解

上一篇:iOS7.1 SDK对应用造成的影响【汇总持续更新】


下一篇:Android查询:模拟键盘鼠标事件(adb shell 实现)