您的位置:首页 > 理论基础 > 计算机网络

根据volley网络请求框架封装好的get请求和post请求

2015-09-08 10:08 666 查看
下面这个类已经封装好了volley的get请求和post请求,直接
import java.util.HashMap;
import java.util.Map;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.StringRequest;

public class HttpUtils {
	
	/**get请求例子*/
	public static void getHomeData(RequestQueue queue,
			Listener<String> listener, ErrorListener error) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("PageSize", "10");
		map.put("pageIndex", "1");
		getHttpRequest(queue, “www.hhhhh.com”, map, listener, error);
	}
	/**post请求例子*/
	public static void getGLHT(RequestQueue queue, Listener<String> listener,
			ErrorListener error, String pageSize) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("pagesize", pageSize);
		map.put("days", "1");
		map.put("cityId", "226");
		map.put("checkintime", "2014/12/29");
		postHttpRequest(queue," www.hhhhh.com”, map, listener, error);
	}

	/** post请求 */
	public static void postHttpRequest(RequestQueue queue, String url,
			final Map<String, String> map, Listener<String> listener,
			ErrorListener error) {
		StringRequest request = new StringRequest(url, listener, error) {
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				// TODO Auto-generated method stub
				if (map != null) {
					return map;
				}
				return super.getParams();
			}
		};
		queue.add(request);
	}

	/** get请求 */
	public static void getHttpRequest(RequestQueue queue, String url,
			Map<String, String> map, Listener<String> listener,
			ErrorListener error) {
		StringRequest request = new StringRequest(paramsCastUrl(url, map),
				listener, error);
		queue.add(request);
	}

	/** 把map参数 拼接成 get请求的 url格式 ,最后和 传过来的url一起拼接 */
	public static String paramsCastUrl(String url, Map<String, String> map) {
		if (map != null) {
			String params = "?";
			/** 遍历map,把 键值对应 */
			for (Map.Entry<String, String> entry : map.entrySet()) {
				params += entry.getKey() + "=" + entry.getValue() + "&";
			}
			/** 把一个字符串 从 0 一直截取到 字符串减一个长度处 */
			params = params.substring(0, params.length() - 1);
			return url + params;
		}
		return url;
	}
	
}


调用就可以
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: