package nc.util.fa.httputil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nc.bs.framework.common.NCLocator;
import nc.bs.framework.server.ISecurityTokenCallback;

/**
 * 城更接口工具类
 * 
 * @author lizc
 *
 */
public class HttpCommnUtil {

	/**
	 * 请求NC HTTPServlet接口时，回调安全令牌
	 */
	public static void backToken() {
		NCLocator.getInstance().lookup(ISecurityTokenCallback.class).token("NCSystem".getBytes(), "pfxx".getBytes());
	}

	/**
	 * 读取请求的json信息
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings("restriction")
	public static String requestJson(HttpServletRequest request) {
		StringBuilder sb = new StringBuilder();
		try {
			request.setCharacterEncoding("utf-8");
			BufferedReader reader = request.getReader();
			char[] buff = new char[1024];
			int len;
			while ((len = reader.read(buff)) != -1) {
				sb.append(buff, 0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

	/**
	 * 回写响应的返回信息
	 * 
	 * @param response
	 * @param returnJson
	 */
	@SuppressWarnings("restriction")
	public static void responseWriter(HttpServletResponse response, String returnJson) {
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-type", "application/json; charset=utf-8");
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
			writer.write(returnJson);
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} finally {
			if (null != writer)
				writer.close();
		}
	}
}
