首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

http设立的响应用消息

2012-12-22 
http设置的响应用消息/**???? * 不带消息体的响应方法???? *????? * @param code 响应码???? * @param req

http设置的响应用消息

/**
???? * 不带消息体的响应方法
???? *?
???? * @param code 响应码
???? * @param request TODO
???? * @param response
???? * @throws IOException 当响应输出异常时抛出
???? */
??? public static void response(int code, HttpServletRequest request, HttpServletResponse response)
??????? throws IOException
??? {
??????? // 必选
??????? response.setHeader(APIVERSION_KEY, apiVersion);
??????? response.setHeader(TIMESTAMP_KEY, sf.format(new Date()));
????????
??????? response.setHeader(RESULT_CODE_KEY, String.valueOf(code));
????????
??????? // add by c59623 为了便于记录系统错误话单,需要在request设置错误码,以便在过滤器能识辨
??????? request.setAttribute(RESULT_CODE_KEY, String.valueOf(code));
??? }
????
??? /**
???? * 处理带消息内容处理。包括设置返回参数返回消息内容
???? *?
???? * @param xml 响应消息内容
???? * @param request http请求
???? * @param response http响应
???? * @throws IOException 当响应输出异常时抛出
???? *?
???? */
??? public static void response(String xml, HttpServletRequest request, HttpServletResponse response)
??????? throws IOException
??? {
??????? String code = (String)request.getAttribute("resultCode");
??????? if (null == code || "".equals(code))
??????? {
??????????? code = String.valueOf(TerminalCodes.SUCCESS);
??????? }
????????
??????? int resultCode = StringTools.toInt(code, TerminalCodes.SUCCESS);
????????
??????? // 默认返回
??????? response(resultCode, request, response);
????????
??????? /*
???????? * 以下为消息体返回处理
???????? */

??????? ByteArrayOutputStream baseOut = new ByteArrayOutputStream(512);
????????
??????? // 默认输出到ByteArrayOutputStream中
??????? OutputStream out = baseOut;
????????
??????? String acceptEncoding = StrUtil.trim(request.getHeader(ACCEPT_ENCODING_KEY));
??????? if (GZIP.equalsIgnoreCase(acceptEncoding))
??????? {
??????????? // 内容压缩类型
??????????? response.setHeader(CONTENT_ENCODING_KEY, acceptEncoding);
????????????
??????????? // 支持gzip压缩时压缩流也输出到ByteArrayOutputStream中
??????????? out = new GZIPOutputStream(baseOut);
??????? }
????????
??????? byte[] xmlHead = XMLHEAD.getBytes(UTF8);
??????? byte[] start = START.getBytes(UTF8);
??????? byte[] xmlBytes = xml.getBytes(UTF8);
??????? byte[] end = END.getBytes(UTF8);
????????
??????? int origSize = xmlHead.length + start.length + xmlBytes.length + end.length;
????????
??????? out.write(xmlHead);
??????? out.write(start);
??????? out.write(xmlBytes);
??????? out.write(end);
????????
??????? // 关闭流,确保所有输出都结束
??????? out.close();
????????
??????? // 必选:消息内容长度
??????? response.setHeader(CONTENT_LENGTH_KEY, String.valueOf(baseOut.size()));
??????? response.setHeader(ORIG_CONTENT_LENGTH_KEY, String.valueOf(origSize));
????????
??????? // 可选
??????? response.setCharacterEncoding(UTF8);
??????? response.setHeader(CONTENT_TYPE_KEY, "application/xml");
????????
??????? // 返回消息内容
??????? baseOut.writeTo(response.getOutputStream());
??? }

热点排行