Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android-網絡通信框架Volley使用詳解

Android-網絡通信框架Volley使用詳解

編輯:關於Android編程

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 Map getParams() {
			Map params = 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,Map additionalHeaders) 
	throws IOException,AuthFailureError {
	for (Entry> header : connection.getHeaderFields().entrySet()) {
	if (header.getKey() != null) {
		String key = header.getKey();
		List 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 parseNetworkResponse(NetworkResponse response) {
	Response superResponse = super.parseNetworkResponse(response);
	Map 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 MapgetHeaders() throws AuthFailureError {
         if(cookies!= null && cookies.length() > 0){
                   HashMap         headers = newHashMap();
                   headers.put("Cookie",cookies);
                   returnheaders;
         }
         returnsuper.getHeaders();
}

7 Volley自定義request:

public class ByteArrayRequest extends Request{
	private final Listener mListener;
	public ByteArrayRequest(int method, String url, Listener listener, ErrorListener errlistener) {
		super(method, url, errlistener);
		mListener = listener;
	}
	@Override
	protected Response 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://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,這裡關於超時時間增長的因子的說法不准確,應該是當第一次連接超時以後,第二次超時時間會變為原來的多少倍,連接超時和讀取超時設置為同一個數。


  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved