标签:
v1olley能干那些事?发送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); } })); }
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; }
转载:http://www.android100.org/html/201406/04/17036.html
关于图片加载:
RequestQueue mQueue = Volley.newRequestQueue(context);
ImageLoader imageLoader = new ImageLoader(mQueue, new BitmapCache());
ImageListener listener = ImageLoader.getImageListener(ivAdvertise,
R.drawable.defaulto, R.drawable.error);//
imageLoader.get(head_img, listener, 200, 200);
public class BitmapCache implements ImageCache {
private LruCache<String, Bitmap> mCache;
public BitmapCache() {
int maxSize = 10 * 1024 * 1024;
mCache = new LruCache<String, Bitmap>(maxSize) {
@Override
protected int sizeOf(String key, Bitmap value) {
// TODO Auto-generated method stub
return value.getRowBytes() * value.getHeight();
}
};
}
@Override
public Bitmap getBitmap(String url) {
// TODO Auto-generated method stub
return mCache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bm) {
// TODO Auto-generated method stub
mCache.put(url, bm);
}
}
//宽高 可不设 关于
NetworkDispatcher还没得及看 详见http://www.android100.org/html/201406/03/16240.html
标签:
原文地址:http://www.cnblogs.com/yizuochengchi2012/p/4990234.html