package com.gh.gamecenter.volley.extended;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.gh.common.util.Utils;

import java.io.UnsupportedEncodingException;

/**
 * 
 * @author 温冠超
 * @email 294299195@qq.com
 * @date 2015-7-31
 */
public class StringExtendedRequest extends ExtendedRequest<String> {

	/** Default charset for JSON request. */
	protected static final String PROTOCOL_CHARSET = "utf-8";

	private String url;
	private String body;

	public StringExtendedRequest(int method, String url, String body,
	                             Response.Listener<String> successListener,
	                             Response.ErrorListener errorListener) {
		super(method, url, successListener, errorListener);
		this.url = url;
		this.body = body;
	}

	public StringExtendedRequest(int method, String url,
	                             Response.Listener<String> successListener,
	                             Response.ErrorListener errorListener) {
		super(method, url, successListener, errorListener);
		this.url = url;
	}

	@Override
	protected Response<String> parseNetworkResponse(NetworkResponse response) {
		Utils.log(url + " = " + response.statusCode);
		String parsed;
		try {
			parsed = getResponseString(response);
		} catch (UnsupportedEncodingException e) {
			parsed = new String(response.data);
		}
		return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
	}

		@Override
	public byte[] getBody() throws AuthFailureError {
		if (body == null) {
			return super.getBody();
		} else {
			try {
				return body.getBytes(PROTOCOL_CHARSET);
			} catch (UnsupportedEncodingException uee) {
				return null;
			}
		}
	}

}
