All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.sunny.tool.HttpTool Maven / Gradle / Ivy

There is a newer version: 0.0.4
Show newest version
package com.sunny.tool;

import com.alibaba.fastjson.JSON;
import com.sunny.model.Result;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

/**
 * HttpTool
 *
 * @author sunny
 * @version 1.0.0
 * @since 2015-07-24
 */
@SuppressWarnings(value = "unused")
public class HttpTool {

    /**
     * 输出内容
     *
     * @param request  请求
     * @param response 响应
     * @param value    内容
     */
    public static void write(HttpServletRequest request, HttpServletResponse response, String value) {
        PrintWriter pw = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            pw = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
            pw.println(value);
            pw.flush();
        } catch (IOException e) {
            LoggerTool.debug("write value error.value is {},error is {}", value, e.getMessage());
        } finally {
            if (pw != null) {
                pw.close();
            }
        }
    }

    /**
     * 输出错误
     *
     * @param request  请求
     * @param response 响应
     * @param code     编码
     * @param message  消息
     * @param object   数据
     */
    public static void writeResult(HttpServletRequest request, HttpServletResponse response, Integer code, String message, Object object) {
        PrintWriter pw = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            pw = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
            Result result = new Result();
            result.setCode(code);
            result.setMessage(message);
            result.setObject(object);
            String value = JSON.toJSONString(result);
            pw.println(value);
            pw.flush();
        } catch (IOException e) {
            LoggerTool.debug("write value error.code is {}", code);
            LoggerTool.debug("write value error.message is {}", message);
            LoggerTool.debug("write value error.object is {}", object);
            LoggerTool.debug("write value error.error is {}", e.getMessage());
        } finally {
            if (pw != null) {
                pw.close();
            }
        }
    }

}