volley 使用方法

允我心安 提交于 2019-12-05 05:53:44

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() {
			@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() {
				@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 MapgetParams() {
			Mapparams = new HashMap();
			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,MapadditionalHeaders) 
	throws IOException,AuthFailureError {
	for (Entry> header : connection.getHeaderFields().entrySet()) {
	if (header.getKey() != null) {
		String key = header.getKey();
		Listvalues = 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 ResponseparseNetworkResponse(NetworkResponse response) {
	ResponsesuperResponse = super.parseNetworkResponse(response);
	MapresponseHeaders = 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 MapgetHeaders() throws AuthFailureError {
         if(cookies!= null && cookies.length() > 0){
                   HashMapheaders = newHashMap();
                   headers.put("Cookie",cookies);
                   returnheaders;
         }
         returnsuper.getHeaders();
}

7 Volley自定义request:

public class ByteArrayRequest extends Request{
	private final ListenermListener;
	public ByteArrayRequest(int method, String url, Listenerlistener, ErrorListener errlistener) {
		super(method, url, errlistener);
		mListener = listener;
	}
	@Override
	protected ResponseparseNetworkResponse(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://stackoverflow.com/questions/16682595/android-volley-imageloader-bitmaplrucache-parameter

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

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

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

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!