Volley的应用(通过Json与服务器交互)

       最近看到论坛有一些介绍Volley框架的文章,被文章中介绍的Volley的优点所吸引,写了一个应用Volley框架的Demo,由于服务设在本地,所以简单介绍下使用的几个类。


       由于本地服务使用用Json进行数据交互,传输的数据通过Base64进行加密,根据不同的请求名返回对应的数据。


       首先需要自定义一个请求类,这里固定使用Post方式,其中几个部分参考了框架中的JsonRequest代码:

/**
 * @author Ryan
 */
public class ExVolleyRequest extends Request {

    /** Charset for request. */
    private static final String PROTOCOL_CHARSET = "utf-8";

    /** Content type for request. */
    private static final String PROTOCOL_CONTENT_TYPE =
        String.format("application/json; charset=%s", PROTOCOL_CHARSET);
	
        // 向服务器端发送的数据
	private Map requestMap;
	
	// 服务器响应的处理监听
	private final Listener mListener;

	/**
	 * 固定使用Post方式
	 * 
	 * @param url 服务器地址
	 * @param requestName 对应功能请求的url
	 * @param listener 服务器响应的监听
	 * @param errorListener 请求失败的监听
	 * @param map 向服务端发送的数据
	 */
	public ExVolleyRequest(String url, String requestName,
			Listener listener, ErrorListener errorListener,
			Map map) {
		super(Method.POST, combinUrl(url, requestName), errorListener);
		this.requestMap = map;
		mListener = listener;
	}

	/**
	 * 向服务发送数据的Map(POST)
	 */
	@Override
	protected Map getParams() throws AuthFailureError {
		if (requestMap != null) {
			return requestMap;
		}
		return super.getParams();
	}

	/**
	 * Request头(参考JsonRequest)
	 */
	@Override
	public Map getHeaders() throws AuthFailureError {
		Map params = new HashMap();
		params.put("Content-Type", "application/x-www-form-urlencoded");
		return params;
	}

	/**
	 * 处理Response(参考JsonRequest)使用Base64Coder解析返回的数据
	 */
	@Override
	protected Response parseNetworkResponse(NetworkResponse response) {
		try {
			String tempString = new String(response.data,
					HttpHeaderParser.parseCharset(response.headers));
			String jsonString = Base64Coder.decode(tempString);
			return Response.success(new JSONObject(jsonString),
					HttpHeaderParser.parseCacheHeaders(response));
		} catch (UnsupportedEncodingException e) {
			return Response.error(new ParseError(e));
		} catch (JSONException je) {
			return Response.error(new ParseError(je));
		} catch (Exception ee) {
			return Response.error(new ParseError(ee));
		}
	}

	/**
	 * 拼接服务器地址和请求名称
	 * @param url
	 * @param requestName
	 * @return
	 */
	private static String combinUrl(String url, String requestName) {
		StringBuilder builder = new StringBuilder("http://");
		builder.append(url);
		builder.append("/");
		builder.append(requestName);
		return builder.toString();
	}

	@Override
	protected void deliverResponse(JSONObject response) {
		mListener.onResponse(response);
	}
	
	@Override
    public String getBodyContentType() {
        return PROTOCOL_CONTENT_TYPE;
    }
}

然后你需要新建一个Volley帮助类:

public class VolleyHelper {

	//private static VolleyHelper instance = null;
	public static RequestQueue mRequestQueue = null;
	private Listener responseListener;
	private ErrorListener errorListener;

	public VolleyHelper(Context context) {
		if (mRequestQueue == null) {
			mRequestQueue = Volley.newRequestQueue(context);
		}
	}

	public boolean httpRequest(String... params) throws Exception {
		if (params.length > 2) {
			HashMap requestDatas = new HashMap();
			if (params.length > 2) {
				for (int i = 2; i < params.length; i++) {
					String data = Base64Coder.encode(params[i]);
					Log.e("encodeData", data);
					if (2 == i) {
						requestDatas.put("DATA", data);
					} else {
						requestDatas.put("DATA" + (3 - i), data);
					}
				}
			}
			ExVolleyRequest request = new ExVolleyRequest(params[0], params[1],
					responseListener, errorListener, requestDatas);
			mRequestQueue.add(request);
			return true;
		}
		return false;
	}

	public void setOnResponseListener(Listener responseListener) {
		this.responseListener = responseListener;
	}

	public void setOnErrorListener(ErrorListener errorListener) {
		this.errorListener = errorListener;
	}

}

有了这两个类,就可以在应用中使用Volley与服务器进行通信了。

private void login() {
		progressDialog = ProgressDialog.show(LoginActivity.this, getResources().getString(R.string.task_waitting), getResources().getString(R.string.task_login), true);
		try {
			VolleyHelper volleyHelper = new VolleyHelper(this);
			volleyHelper.setOnErrorListener(new ErrorListener() {
				@Override
				public void onErrorResponse(VolleyError error) {
					progressDialog.dismiss();
					error.printStackTrace();
				}
			});
			volleyHelper.setOnResponseListener(new Listener() {

				@Override
				public void onResponse(JSONObject response) {
					progressDialog.dismiss();
					Log.e("Login", "onResponse:" + response.toString());
				}
			});
			volleyHelper.httpRequest(preferences.getHttpUrl(), RequestConstants.LOGIN, user.toJsonString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}






你可能感兴趣的:(Android)