使用Volley请求,获取POST请求cookie值

根据字符串获取请求返回值当值的cookie值,话不多说,直接上代码,如下:

public class JsonPostRequest extends Request {

    private HashMap mMap;
    private Response.Listener mListener;
    public String cookieFromResponse;
    private String mHeader;
    private Map sendHeader=new HashMap(1);

    public JsonPostRequest(String url, Response.Listener listener,
                           Response.ErrorListener errorListener, HashMap map) {

        super(Method.POST, url, errorListener);
        mListener = listener;
        mMap = map;
    }

    //当http请求是post时,则需要该使用该函数设置往里面添加的键值对
    @Override
    protected Map getParams() throws AuthFailureError {
        return mMap;
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        try {
            // 参数的转换
            byte[] bodyBytes = JsonPostRequest.encryptParams(mMap);
            return bodyBytes ;
        } catch (Throwable e){
        }
        return super.getBody();
    }

    /**
     * 对post请求数据进行加密
     * @param params
     * @return
     * @throws Throwable
     */
    public static byte[] encryptParams(HashMap params) throws Throwable{
        if (params == null){
            return null;
        }

        StringBuilder stringBuilder = new StringBuilder();
        Iterator> iterator = params.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry entry = iterator.next();
            String key = entry.getKey();
            String value = entry.getValue();
            if (stringBuilder.length() > 0){
                stringBuilder.append("&");
            }
            stringBuilder.append(key).append("=").append(Uri.encode(value));
        }

        byte[] buff = stringBuilder.toString().getBytes("utf-8");

        return buff;
    }

    @Override
    protected Response parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString =
                    new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            mHeader = response.headers.toString();

            //使用正则表达式从reponse的头中提取cookie内容的子串
            Pattern pattern=Pattern.compile("Set-Cookie.*?;");
            Matcher m=pattern.matcher(mHeader);
            if(m.find()){
                cookieFromResponse = m.group();
            }

            JSONObject jsonObject = new JSONObject(jsonString);
            if (!TextUtils.isEmpty(cookieFromResponse)){
                //去掉cookie末尾的分号
                cookieFromResponse = cookieFromResponse.substring(11,cookieFromResponse.length()-1);
                //将cookie字符串添加到jsonObject中,该jsonObject会被deliverResponse递交,调用请求时则能在onResponse中得到
                jsonObject.put("Cookie",cookieFromResponse);
            }
            return Response.success(jsonObject,
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

    @Override
    protected void deliverResponse(JSONObject response) {
        mListener.onResponse(response);
    }

    @Override
    public Map getHeaders() throws AuthFailureError {
        return sendHeader;
    }

    public void setSendCookie(String cookie){
        sendHeader.put("Cookie",cookie);
    }
}

参考的文章链接如下:

http://my.oschina.net/liusicong/blog/361853

你可能感兴趣的:(使用Volley请求,获取POST请求cookie值)