1 package com.foxinmy.weixin4j.util;
2
3 import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
4 import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
5 import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
6 import static io.netty.handler.codec.http.HttpHeaderNames.DATE;
7 import static io.netty.handler.codec.http.HttpHeaderNames.USER_AGENT;
8 import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
9 import io.netty.buffer.Unpooled;
10 import io.netty.handler.codec.http.DefaultFullHttpResponse;
11 import io.netty.handler.codec.http.FullHttpResponse;
12 import io.netty.handler.codec.http.HttpHeaderValues;
13 import io.netty.handler.codec.http.HttpResponse;
14 import io.netty.handler.codec.http.HttpResponseStatus;
15
16 import java.util.Date;
17
18 import com.foxinmy.weixin4j.startup.WeixinServerBootstrap;
19
20
21
22
23
24
25
26
27
28
29 public class HttpUtil {
30
31 private static String SERVER = "netty4";
32 private static String WEIXIN4J = "weixin4j-server";
33
34
35
36
37
38
39
40
41
42
43 public static HttpResponse createHttpResponse(String content,
44 String contentType) {
45 FullHttpResponse httpResponse = new DefaultFullHttpResponse(HTTP_1_1,
46 HttpResponseStatus.OK, Unpooled.copiedBuffer(content,
47 ServerToolkits.UTF_8));
48 httpResponse.headers().set(
49 CONTENT_TYPE,
50 String.format("%s;encoding=%s", contentType,
51 ServerToolkits.UTF_8.displayName()));
52 httpResponse.headers().set(CONTENT_LENGTH,
53 content.getBytes(ServerToolkits.UTF_8).length);
54 resolveHeaders(httpResponse);
55 return httpResponse;
56 }
57
58 public static void resolveHeaders(FullHttpResponse httpResponse) {
59
60
61
62
63
64
65 httpResponse.headers().set(CONNECTION, HttpHeaderValues.CLOSE);
66 httpResponse.headers().set(DATE, new Date());
67 httpResponse.headers().set(SERVER, SERVER);
68 httpResponse.headers()
69 .set(USER_AGENT,
70 String.format("%s/%s", WEIXIN4J,
71 WeixinServerBootstrap.VERSION));
72 }
73 }