封装了http Get请求和Post请求

接口文件:

IVolleyObject


public interface IVolleyObject{
   static int communicationErr=1;
   static int jsonFromatErr=2;
   static int serverReportErr=3;




   /**
    *http相应失败
    * @param errType  1:volley通讯错误;2:返回json格式错误
    * @param volleyError
     */
   public  void onErrorResponse(int errType, String volleyError);
   /**
    * http Volley返回JsonObject类型
    */
   public void onObjectResponse(JSONObject objectBean);
   
}


接口 :IVolleyString
public interface IVolleyString {
   static int communicationErr=1;
   static int jsonFromatErr=2;
   static int serverReportErr=3;


   /**
    * http Volley返回String类型
    */
   public  void onStringResponse(String strJson);
   
   /**
     * http相应失败
    *
     */
   /**
    *
    * @param errType  1:volley通讯错误;2:返回json格式错误
    * @param volleyError
     */
   public  void onErrorResponse(int errType, String  volleyError);

   
}

服务器返回结构体HttpRes
public class HttpRes<T> implements Serializable {

    int Code;//"异常编号0为正常,非0错误"
    String  ErrorDesc; //"异常消息"
    T Result;//"返回结果"

    public HttpRes() {
    }

    public HttpRes(int code, String errorDesc, T result) {
        Code = code;
        ErrorDesc = errorDesc;
        Result = result;
    }

    public  Type getResultClass()
    {
        Type type = new TypeTokenT>>() {
        }.getType();
        return type;
    }

    public  Type getResultClass2()
    {
        Type type = new TypeTokenT>>() {
        }.getType();
        return type;
    }

    public int getCode() {
        return Code;
    }

    public void setCode(int code) {
        Code = code;
    }

    public String getErrorDesc() {
        return ErrorDesc;
    }

    public void setErrorDesc(String errorDesc) {
        ErrorDesc = errorDesc;
    }

    public T getResult() {
        return Result;
    }

    public void setResult(T result) {
        Result = result;
    }

    @Override
    public String toString() {
        Gson gson=new Gson();
        return HttpRes.class.getSimpleName()+":"+gson.toJson(this);
    }
}

Volley Get 请求:VolleyHttpGetRequest

package hd.com.xposeddemo.http;

import android.util.Log;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import hd.com.xposeddemo.AppWechatForword;
import hd.com.xposeddemo.beanHttp.HttpRes;
import hd.com.xposeddemo.interfaces.IVolleyObject;
import hd.com.xposeddemo.interfaces.IVolleyString;

/**
 * @author:czg
 * @date:2016/11/29
 * @description:
 * 调用volleyGetWithStringRequest 和 volleyGetWithJsonObjectRequest 之前必须设置url 和设置map(key,value)
 *
 */
public class VolleyHttpGetRequest {
    static private String TAG = "VolleyPost";
    static private String volleyHttpGet = "volleyHttpGet";



    /**
     *  使用Get方式返回String类型的请求结果数据
     *
     *  new StringRequest(int method,String url,Listener listener,ErrorListener errorListener)
     *  method:请求方式,Get请求为Method.GET,Post请求为Method.POST
     *  url:请求地址
     *  listener:请求成功后的回调
     *  errorListener:请求失败的回调
     */
    static public void volleyGetWithStringRequest(String mUrl, final IVolleyString iVolleyString) {
//        this.mUrl = mUrl;
//        this.iVolleyString = iVolleyString;

        //mUrl = "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=15850781443";
        StringRequest request = new StringRequest(Request.Method.GET, mUrl,
                new Response.Listener() {
                    @Override
                    public void onResponse(String s) {//s为请求返回的字符串数据
                        //Toast.makeText(VolleyActivity.this,"StringReques(get方法)"+s,Toast.LENGTH_LONG).show();
                        //Log.i(TAG,"使用Get方式返回String类型 ,返回结果:"+s);
                        if (iVolleyString !=null){
                            try{
                                Gson gson = new Gson();
                                HttpRes httpRes = gson.fromJson(s, HttpRes.class);
                                //mIVolley.onStringResponse(s);

                                if (httpRes.getCode()!=0){
                                    iVolleyString.onErrorResponse(IVolleyString.serverReportErr,httpRes.getErrorDesc());
                                }else{
                                    iVolleyString.onStringResponse(s);
                                }

                            }catch (Exception e) {
                                String err = "Http响应json数据-->>转换成httpRes错误!!";
                                Log.e(TAG,err, e);
                                iVolleyString.onErrorResponse(IVolleyString.jsonFromatErr,err);
                            }
                        }


                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        //Toast.makeText(VolleyActivity.this,volleyError.toString(),Toast.LENGTH_LONG).show();
                        //Log.i(TAG,"使用Get方式返回String类型,发生错误:"+volleyError.toString());
                        if (iVolleyString != null){
                            iVolleyString.onErrorResponse(IVolleyString.communicationErr,volleyError.toString());
                        }
                    }
                });
        //设置请求的Tag标签,可以在全局请求队列中通过Tag标签进行请求的查找
        request.setTag(volleyHttpGet);
        //将请求加入全局队列中
        AppWechatForword.getHttpQueues().add(request);
    }


    /**
     *  使用Get方式返回JsonObject类型的请求结果数据
     *
     *  new JsonObjectRequest(int method,String url,JsonObject jsonObject,Listener listener,ErrorListener errorListener)
     *  method:请求方式,Get请求为Method.GET,Post请求为Method.POST
     *  url:请求地址
     *  JsonObject:Json格式的请求参数。如果使用的是Get请求方式,请求参数已经包含在url中,所以可以将此参数置为null
     *  listener:请求成功后的回调
     *  errorListener:请求失败的回调
     */
    static public void volleyGetWithJsonObjectRequest(String mUrl,  final IVolleyObject iVolleyObject) {
        //mUrl = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=218.4.255.255";
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, mUrl, null,
                new Response.Listener() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {//jsonObject为请求返回的Json格式数据
                        //Toast.makeText(VolleyActivity.this,"JsonObjectRequest(get方法):"+jsonObject.toString(),Toast.LENGTH_LONG).show();
                        //Log.i(TAG,"Velloy Get方式返回JsonObject:"+jsonObject.toString());
                        if (iVolleyObject !=null){
                            try {
                                int Code = jsonObject.getInt("Code");
                                if (Code != 0){
                                    String  ErrorDesc = jsonObject.getString("ErrorDesc");
                                    iVolleyObject.onErrorResponse(IVolleyObject.serverReportErr,ErrorDesc);
                                }else{
                                    iVolleyObject.onObjectResponse(jsonObject);
                                }


                            } catch (JSONException e) {
                                String err = "解析json返回object 是发生数据格式错误";
                                e.printStackTrace();
                                iVolleyObject.onErrorResponse(IVolleyObject.jsonFromatErr,err);
                            }



                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        //Toast.makeText(VolleyActivity.this,volleyError.toString(),Toast.LENGTH_LONG).show();
                        //Log.i(TAG,"Velloy Get方式返回JsonObject类型,发生错误"+volleyError.toString());
                        if (iVolleyObject !=null){
                            iVolleyObject.onErrorResponse(IVolleyString.communicationErr,volleyError.toString());
                        }
                    }
                });

        //设置请求的Tag标签,可以在全局请求队列中通过Tag标签进行请求的查找
        request.setTag(volleyHttpGet);
        //将请求加入全局队列中
        AppWechatForword.getHttpQueues().add(request);
    }




    static public void cancel(){
        AppWechatForword.getHttpQueues().cancelAll(volleyHttpGet);
    }
}

Volley Http Post 请求 VolleyHttpPostRequest
package hd.com.xposeddemo.http;

import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.Map;

import hd.com.xposeddemo.AppWechatForword;
import hd.com.xposeddemo.beanHttp.HttpRes;
import hd.com.xposeddemo.interfaces.IVolleyObject;
import hd.com.xposeddemo.interfaces.IVolleyString;

/**
 * @author:czg
 * @date:2016/11/29
 * @description:
 * 网络范围实例 :http://192.168.0.248:8444/App/GetPlugInConfigVersion?plugInFlag=3&weChatVersion=321
 * 调用volleyGetWithStringRequest 和 volleyGetWithJsonObjectRequest 之前必须设置url
 *
 */
public class VolleyHttpPostRequest {
    static private String TAG = "VolleyGet";
    static private String volleyHttpPost = "volleyHttpPost";







    /**
     * 使用Post方式返回String类型的请求结果数据
     *
     *  new StringRequest(int method,String url,Listener listener,ErrorListener errorListener)
     *  method:请求方式,Get请求为Method.GET,Post请求为Method.POST
     *  url:请求地址
     *  listener:请求成功后的回调
     *  errorListener:请求失败的回调
     */
    static public void volleyPostWithStringRequest(String mUrl, final Map, String> map, final IVolleyString iVolleyString) {
//        this.mUrl = mUrl;
//        this.iVolleyString = iVolleyString;

        //mUrl = "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm";
        StringRequest request = new StringRequest(Request.Method.POST, mUrl,
                new Response.Listener() {
                    @Override
                    public void onResponse(String s) {//s为请求返回的字符串数据
                        //Toast.makeText(VolleyActivity.this,"StringRequest(Post方法)"+s,Toast.LENGTH_LONG).show();
                        Log.i(TAG,"使用Post方式返回String类型,返回结果:"+s);
                        if (iVolleyString !=null){
                            //mIVolley.onStringResponse(s);
                            try{


                                Gson gson = new Gson();

                                Type type = new TypeToken() {
                                }.getType();
                                HttpRes httpRes = new Gson().fromJson(s,type);
                                if (httpRes.getCode()!=0){
                                    iVolleyString.onErrorResponse(IVolleyString.serverReportErr,httpRes.getErrorDesc());
                                }else{
                                    iVolleyString.onStringResponse(s);
                                }


                            }catch (Exception e) {
                                String err = "Http响应json string数据-->>转换成httpRes错误!!";
                                Log.e(TAG,err, e);
                                iVolleyString.onErrorResponse(IVolleyString.jsonFromatErr, err);
                            }
                        }



                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        //Toast.makeText(VolleyActivity.this,volleyError.toString(),Toast.LENGTH_LONG).show();
                        Log.e(TAG,"使用Post方式返回String类型,发生失败"+volleyError.toString());
                        if (iVolleyString !=null){
                            iVolleyString.onErrorResponse(IVolleyString.communicationErr,volleyError.toString());
                        }
                    }
                }){
            @Override
            protected Map, String> getParams() throws AuthFailureError {
                //Map map = new HashMap<>();
                //将请求参数名与参数值放入map中
                //map.put("tel","15850781443");
                return map;
            }
        }
                ;
        //设置请求的Tag标签,可以在全局请求队列中通过Tag标签进行请求的查找
        request.setTag(volleyHttpPost);
        //将请求加入全局队列中
        AppWechatForword.getHttpQueues().add(request);
    }

    /**
     *  使用Post方式返回JsonObject类型的请求结果数据
     *
     *  new JsonObjectRequest(int method,String url,JsonObject jsonObject,Listener listener,ErrorListener errorListener)
     *  method:请求方式,Get请求为Method.GET,Post请求为Method.POST
     *  url:请求地址
     *  JsonObject:Json格式的请求参数。如果使用的是Get请求方式,请求参数已经包含在url中,所以可以将此参数置为null
     *  listener:请求成功后的回调
     *  errorListener:请求失败的回调
     */
    static public void volleyPostWithJsonObjectRequest(String mUrl, Map, String> map, final IVolleyObject iVolleyObject) {
        //mUrl = "http://www.kuaidi100.com/query";
//        Map map = new HashMap<>();
//        map.put("type","yuantong");
//        map.put("postid","229728279823");
        //将map转化为JSONObject对象
        JSONObject jsonObject = new JSONObject(map);

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, mUrl, jsonObject,
                new Response.Listener() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {//jsonObject为请求返回的Json格式数据
                        //Toast.makeText(VolleyActivity.this,jsonObject.toString(),Toast.LENGTH_LONG).show();
                        //Log.i(TAG,"使用Post方式返回JsonObject类型,结果"+jsonObject.toString());
                        if (iVolleyObject !=null){
                            //mIVolley.onObjectResponse(jsonObject);
                            try {
                                int Code = jsonObject.getInt("Code");
                                if (Code != 0){
                                    String  ErrorDesc = jsonObject.getString("ErrorDesc");
                                    iVolleyObject.onErrorResponse(IVolleyObject.serverReportErr,ErrorDesc);
                                }else{
                                    iVolleyObject.onObjectResponse(jsonObject);
                                }


                            } catch (JSONException e) {
                                String err = "解析json返回object 是发生数据格式错误";
                                e.printStackTrace();
                                iVolleyObject.onErrorResponse(IVolleyObject.jsonFromatErr,err);
                            }


                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        //Toast.makeText(VolleyActivity.this,volleyError.toString(),Toast.LENGTH_LONG).show();
                        Log.e(TAG,"使用Post方式返回JsonObject类型,发生错误:"+volleyError.toString());
                        if (iVolleyObject !=null){
                            iVolleyObject.onErrorResponse(IVolleyString.communicationErr,volleyError.toString());
                        }
                    }
                });
        //设置请求的Tag标签,可以在全局请求队列中通过Tag标签进行请求的查找
        request.setTag(volleyHttpPost);
        //将请求加入全局队列中
        AppWechatForword.getHttpQueues().add(request);
    }
    static public void cancel(){
        AppWechatForword.getHttpQueues().cancelAll(volleyHttpPost);
    }


}



你可能感兴趣的:(Android开发知识体系)