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

来源:互联网 发布:日本人生活方式 知乎 编辑:程序博客网 时间:2024/05/16 07:20
下面这个类已经封装好了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) {@Overrideprotected Map<String, String> getParams() throws AuthFailureError {// TODO Auto-generated method stubif (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;}}

调用就可以
0 0
原创粉丝点击