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

下面这个类已经封装好了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 listener, ErrorListener error) {
		Map map = new HashMap();
		map.put("PageSize", "10");
		map.put("pageIndex", "1");
		getHttpRequest(queue, “www.hhhhh.com”, map, listener, error);
	}
	/**post请求例子*/
	public static void getGLHT(RequestQueue queue, Listener listener,
			ErrorListener error, String pageSize) {
		Map map = new HashMap();
		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 map, Listener listener,
			ErrorListener error) {
		StringRequest request = new StringRequest(url, listener, error) {
			@Override
			protected Map 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 map, Listener 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 map) {
		if (map != null) {
			String params = "?";
			/** 遍历map,把 键值对应 */
			for (Map.Entry entry : map.entrySet()) {
				params += entry.getKey() + "=" + entry.getValue() + "&";
			}
			/** 把一个字符串 从 0 一直截取到 字符串减一个长度处 */
			params = params.substring(0, params.length() - 1);
			return url + params;
		}
		return url;
	}
	
}

调用就可以

你可能感兴趣的:(Android)