// web POST 代码
public static StringhttpPost(String param) {
String strRes ="";
try {
//创建httpClient请求
CloseableHttpClient httpClient = HttpClients.createDefault();
//请求地址
String url ="http://127.0.0.1:17045";
//创建httpPost
HttpPost httpPost =new HttpPost(url);
//将参数集合添加到httpPost
httpPost.setEntity(new StringEntity(param));
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
// 响应
CloseableHttpResponse response =null;
try {
// 由客户端执行(发送)Post请求
response = httpClient.execute(httpPost);
// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
System.out.println("status:" + response.getStatusLine());
if (responseEntity !=null) {
System.out.println("content len:" + responseEntity.getContentLength());
strRes = EntityUtils.toString(responseEntity);
System.out.println("content:" + strRes);
return strRes;
}
}catch (Exception e) {
e.printStackTrace();
}finally {
try {
// 释放资源
if (httpClient !=null) {
httpClient.close();
}
if (response !=null) {
response.close();
}
}catch (IOException e) {
e.printStackTrace();
}
}
}catch (Exception e) {
e.printStackTrace();
}
return "";
}
//过滤器
package com.qg.comm;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* ClassName:CORSFilter
* Package:com.qg.comm
* Description:
*
* @Create:2023/7/5 0005 上午 10:40
* @Autor:QG
*/
public class CORSFilterimplements Filter {
private FilterConfigfilterConfig;
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) sresponse;
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE,OPTIONS");
response.addHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header");
response.addHeader("Access-Control-Max-Age", "1800");// 30 min
chain.doFilter(srequest, sresponse);
}
@Override
public void init(FilterConfig filterConfig)throws ServletException {
this.filterConfig = filterConfig;
}
}
//web.xml 配置
<filter-name>CORS
<filter-class>com.qg.comm.CORSFilter
<param-name>encoding
<param-value>UTF-8
<filter-name>CORS
<url-pattern>/*
</filter-mapping>
//netty 响应
package com.qg.msgProcess;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.qg.def.E_RoomType;
import com.qg.def.E_WebMsg;
import com.qg.kernelManager.GameManager;
import com.qg.matches.normalMatch.NormalMatchBean;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;
import org.apache.logging.log4j.LogManager;
import java.nio.charset.StandardCharsets;
public class NotificationHandlerextends SimpleChannelInboundHandler {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ctx.close();
cause.printStackTrace();
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
if (evtinstanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent) evt;
if (event.state() == IdleState.ALL_IDLE) {
if (ctx.channel().isOpen()) {
ctx.channel().close();
}
}
}
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) {
ByteBuf buf = request.content();
byte[] arr =new byte[buf.readableBytes()];
buf.getBytes(0, arr);
PostDataBean bean =null;
try {
bean = JSONObject.parseObject(new String(arr, StandardCharsets.UTF_8), PostDataBean.class);
}catch (Exception e) {
LogManager.getLogger().error("web error : " + e.getMessage(), e);
ctx.close();
}
if (bean ==null) {
ctx.close();
return;
}
if (!bean.token.equals("sjguandan123")) {
LogManager.getLogger().info("token error");
ctx.close();
return;
}
int code = bean.code;
if (code <= E_WebMsg.undefined.getValue() || code >= E_WebMsg.end.getValue()) {
return;
}
E_WebMsg webMsg = E_WebMsg.values()[code];
PostDataBean finalBean = bean;
ctx.channel().eventLoop().execute(new Runnable() {
@Override
public void run() {
LogManager.getLogger().debug("msg = " +webMsg);
String resText ="";
try {
switch (webMsg) {
case ReqMatchConfig: {
E_RoomType roomType = E_RoomType.values()[Integer.parseInt(finalBean.data)];
LogManager.getLogger().debug("room type = " + roomType);
NormalMatchBean res = GameManager.getInst().normalMatchMg.getConfigBean(roomType);
if(res !=null){
resText = JSON.toJSONString(res);
LogManager.getLogger().debug("准备发送 " + resText);
}
}
break;
}
ByteBuf resContent = Unpooled.copiedBuffer(resText, CharsetUtil.UTF_8);
FullHttpResponse response =new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
HttpResponseStatus.OK, resContent);
response.headers().set("Access-Control-Allow-Origin", "*");
response.headers().set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD,PUT");
response.headers().set("Access-Control-Max-Age", "3600");
response.headers().set("Access-Control-Allow-Headers",
"access-control-allow-origin, authority, content-type, version-info, X-Requested-With");
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, resContent.readableBytes());
ctx.writeAndFlush(response);
ctx.channel().close();
}catch (Exception e) {
e.printStackTrace();
ByteBuf resContent = Unpooled.copiedBuffer("error", CharsetUtil.UTF_8);
FullHttpResponse response =new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
HttpResponseStatus.OK, resContent);
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, resContent.readableBytes());
ctx.writeAndFlush(response);
ctx.channel().close();
}
}
});
}
}