View Javadoc
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   * HTTP工具类
22   *
23   * @className HttpUtil
24   * @author jinyu(foxinmy@gmail.com)
25   * @date 2014年11月15日
26   * @since JDK 1.6
27   * @see
28   */
29  public class HttpUtil {
30  
31  	private static String SERVER = "netty4";
32  	private static String WEIXIN4J = "weixin4j-server";
33  
34  	/**
35  	 * 创建有内容的HttpResponse响应
36  	 *
37  	 * @param content
38  	 *            响应内容
39  	 * @param contentType
40  	 *            响应类型
41  	 * @return HttpResponse
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  		 * if (HttpHeaders.isKeepAlive(httpRequest)) {
61  		 * httpResponse.headers().set(CONNECTION, Values.KEEP_ALIVE); } if
62  		 * (HttpHeaders.isTransferEncodingChunked(httpRequest)) {
63  		 * httpResponse.headers().set(TRANSFER_ENCODING, Values.CHUNKED); }
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  }