xieb
2024-12-02 9f204e8842e1688858889a67b702d9e19bb18b15
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package cn.gistack.by.nettyUpload.utils;
 
import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.util.CharsetUtil;
 
import java.util.Map;
 
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
 
/**
 * response工具
 * @author chenhaijian
 * @date 2020-05-21 17:11
 */
public class HttpResponseUtils {
 
    /**
     * 向客户端发送消息提示
     * @param ctx
     * @param status
     */
    public static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
        FullHttpResponse response = new DefaultFullHttpResponse(
                HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8));
        response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
 
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }
 
    /**
     * 向客户端发送消息提示
     * @param ctx
     * @param status
     * @param message
     */
    public static void sendResponseJson(ChannelHandlerContext ctx, HttpResponseStatus status, String message) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", status.code());
        jsonObject.put("msg", message);
 
        FullHttpResponse response = new DefaultFullHttpResponse(
                HTTP_1_1, status, Unpooled.copiedBuffer(jsonObject.toJSONString(), CharsetUtil.UTF_8));
        response.headers().set(CONTENT_TYPE, "application/json; charset=UTF-8");
 
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }
 
    public static void sendResponseJson2(ChannelHandlerContext ctx, HttpResponseStatus status,
                                         String message,Map<String, Object> map) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", status.code());
        jsonObject.put("msg", message);
        jsonObject.put("data", map);
 
        FullHttpResponse response = new DefaultFullHttpResponse(
            HTTP_1_1, status, Unpooled.copiedBuffer(jsonObject.toJSONString(), CharsetUtil.UTF_8));
        response.headers().set(CONTENT_TYPE, "application/json; charset=UTF-8");
 
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }
}