org.tio.http.common.HttpRequest Java Examples
The following examples show how to use
org.tio.http.common.HttpRequest.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FreemarkerConfig.java From t-io with Apache License 2.0 | 6 votes |
/** * * @param request * @return */ public Configuration getConfiguration(HttpRequest request) { if (this.domainConfMap == null || domainConfMap.size() == 0) { return configuration; } String domain = request.getDomain(); Configuration root = domainConfMap.get(domain); if (root != null) { return root; } Set<Entry<String, Configuration>> set = domainConfMap.entrySet(); for (Entry<String, Configuration> entry : set) { String d = entry.getKey(); if (d.startsWith(".") && domain.endsWith(d)) { Configuration cfg = entry.getValue(); domainConfMap.put(domain, cfg); return cfg; } } domainConfMap.put(domain, configuration); return configuration; }
Example #2
Source File: DefaultHttpRequestHandler.java From t-io with Apache License 2.0 | 6 votes |
private Method getMethod(HttpRequest request, RequestLine requestLine) { Method method = null; String path = requestLine.path; if (routes != null) { method = routes.getMethodByPath(path, request); path = requestLine.path; } if (method == null) { if (StrUtil.isNotBlank(httpConfig.getWelcomeFile())) { if (StrUtil.endWith(path, "/")) { path = path + httpConfig.getWelcomeFile(); requestLine.setPath(path); if (routes != null) { method = routes.getMethodByPath(path, request); path = requestLine.path; } } } } return method; }
Example #3
Source File: DefaultHttpRequestHandler.java From t-io with Apache License 2.0 | 6 votes |
@Override public HttpResponse resp500(HttpRequest request, RequestLine requestLine, Throwable throwable) throws Exception { if (throwableHandler != null) { return throwableHandler.handler(request, requestLine, throwable); } if (routes != null) { String page500 = httpConfig.getPage500(); Method method = routes.PATH_METHOD_MAP.get(page500); if (method != null) { return Resps.forward(request, page500); } } return Resps.resp500(request, requestLine, httpConfig, throwable); }
Example #4
Source File: Resps.java From t-io with Apache License 2.0 | 6 votes |
/** * 根据文件创建响应 * @param request * @param fileOnServer * @return * @throws IOException * @author tanyaowu */ public static HttpResponse file(HttpRequest request, File fileOnServer) throws Exception { if (fileOnServer == null || !fileOnServer.exists()) { return request.httpConfig.getHttpRequestHandler().resp404(request, request.getRequestLine()); } Date lastModified = new Date(fileOnServer.lastModified()); HttpResponse ret = try304(request, lastModified.getTime()); if (ret != null) { return ret; } byte[] bodyBytes = Files.readAllBytes(fileOnServer.toPath()); String filename = fileOnServer.getName(); String extension = FileUtil.extName(filename); ret = bytes(request, bodyBytes, extension); // ret.addHeader(HeaderName.Content_Disposition, HeaderValue.from("attachment;filename=" + fileOnServer.getName())); ret.setLastModified(HeaderValue.from(lastModified.getTime() + "")); return ret; }
Example #5
Source File: DefaultHttpRequestHandler.java From t-io with Apache License 2.0 | 6 votes |
private void processCookieAfterHandler(HttpRequest request, RequestLine requestLine, HttpResponse httpResponse) throws ExecutionException { if (httpResponse == null) { return; } if (!httpConfig.isUseSession()) { return; } HttpSession httpSession = request.getHttpSession();//(HttpSession) channelContext.get();//.getHttpSession();//not null // Cookie cookie = getSessionCookie(request, httpConfig); String sessionId = getSessionId(request); if (StrUtil.isBlank(sessionId)) { createSessionCookie(request, httpSession, httpResponse, false); // log.info("{} 创建会话Cookie, {}", request.getChannelContext(), cookie); } else { HttpSession httpSession1 = (HttpSession) httpConfig.getSessionStore().get(sessionId); if (httpSession1 == null) {//有cookie但是超时了 createSessionCookie(request, httpSession, httpResponse, false); } } }
Example #6
Source File: HttpGzipUtils.java From t-io with Apache License 2.0 | 6 votes |
/** * * @param request * @param response * @author tanyaowu */ public static void gzip(HttpRequest request, HttpResponse response) { if (response == null) { return; } // // // 已经gzip过了,就不必再压缩了 // if (response.isHasGzipped()) { // return; // } if (request != null && request.getIsSupportGzip()) { gzip(response); } else { if (request != null) { log.warn("{}, 不支持gzip, {}", request.getClientIp(), request.getHeader(HttpConst.RequestHeaderKey.User_Agent)); } else { log.info("request对象为空"); } } }
Example #7
Source File: DefaultHttpRequestHandler.java From t-io with Apache License 2.0 | 6 votes |
private void processCookieBeforeHandler(HttpRequest request, RequestLine requestLine) throws ExecutionException { if (!httpConfig.isUseSession()) { return; } String sessionId = getSessionId(request); // Cookie cookie = getSessionCookie(request, httpConfig); HttpSession httpSession = null; if (StrUtil.isBlank(sessionId)) { httpSession = createSession(request); } else { // if (StrUtil.isBlank(sessionId)) { // sessionId = cookie.getValue(); // } httpSession = (HttpSession) httpConfig.getSessionStore().get(sessionId); if (httpSession == null) { if (log.isInfoEnabled()) { log.info("{} session【{}】超时", request.channelContext, sessionId); } httpSession = createSession(request); } } request.setHttpSession(httpSession); }
Example #8
Source File: Resps.java From t-io with Apache License 2.0 | 6 votes |
/** * 创建字符串输出 * @param request * @param bodyString * @param charset * @param Content_Type * @return * @author tanyaowu */ public static HttpResponse string(HttpRequest request, String bodyString, String charset, String Content_Type) { HttpResponse ret = new HttpResponse(request); // // //处理jsonp // String jsonp = request.getParam(request.httpConfig.getJsonpParamName()); // if (StrUtil.isNotBlank(jsonp)) { // bodyString = jsonp + "(" + bodyString + ")"; // } if (bodyString != null) { if (charset == null) { ret.setBody(bodyString.getBytes()); } else { try { ret.setBody(bodyString.getBytes(charset)); } catch (UnsupportedEncodingException e) { log.error(e.toString(), e); } } } ret.addHeader(HeaderName.Content_Type, HeaderValue.Content_Type.from(Content_Type)); return ret; }
Example #9
Source File: Resps.java From t-io with Apache License 2.0 | 6 votes |
/** * 尝试返回304,这个会new一个HttpResponse返回 * @param request * @param lastModifiedOnServer 服务器中资源的lastModified * @return * @author tanyaowu */ public static HttpResponse try304(HttpRequest request, long lastModifiedOnServer) { String If_Modified_Since = request.getHeader(HttpConst.RequestHeaderKey.If_Modified_Since);//If-Modified-Since if (StrUtil.isNotBlank(If_Modified_Since)) { Long If_Modified_Since_Date = null; try { If_Modified_Since_Date = Long.parseLong(If_Modified_Since); if (lastModifiedOnServer <= If_Modified_Since_Date) { HttpResponse ret = new HttpResponse(request); ret.setStatus(HttpResponseStatus.C304); return ret; } } catch (NumberFormatException e) { log.warn("{}, {}不是整数,浏览器信息:{}", request.getClientIp(), If_Modified_Since, request.getUserAgent()); return null; } } return null; }
Example #10
Source File: DomainMappingSessionCookieDecorator.java From t-io with Apache License 2.0 | 5 votes |
/** * @param sessionCookie * @author: tanyaowu */ @Override public void decorate(Cookie sessionCookie, HttpRequest request, String domain) { Set<Entry<String, String>> set = domainMap.entrySet(); String initDomain = sessionCookie.getDomain(); for (Entry<String, String> entry : set) { String key = entry.getKey(); String value = entry.getValue(); if (StrUtil.equalsIgnoreCase(key, initDomain) || ReUtil.isMatch(key, initDomain)) { sessionCookie.setDomain(value); } } }
Example #11
Source File: HttpServerAioListener.java From t-io with Apache License 2.0 | 5 votes |
@Override public void onAfterSent(ChannelContext channelContext, Packet packet, boolean isSentSuccess) { // if ((channelContext.sslFacadeContext == null || channelContext.sslFacadeContext.isHandshakeCompleted())/** && packet instanceof HttpResponse*/ // ) {} HttpResponse httpResponse = (HttpResponse) packet; HttpRequest request = httpResponse.getHttpRequest(); // String connection = request.getConnection(); if (request != null) { if (request.httpConfig.compatible1_0) { switch (request.requestLine.version) { case HttpConst.HttpVersion.V1_0: if (!HttpConst.RequestHeaderValue.Connection.keep_alive.equals(request.getConnection())) { Tio.remove(channelContext, "http 请求头Connection!=keep-alive:" + request.getRequestLine()); } break; default: if (HttpConst.RequestHeaderValue.Connection.close.equals(request.getConnection())) { Tio.remove(channelContext, "http 请求头Connection=close:" + request.getRequestLine()); } break; } } else { if (HttpConst.RequestHeaderValue.Connection.close.equals(request.getConnection())) { Tio.remove(channelContext, "http 请求头Connection=close:" + request.getRequestLine()); } } } }
Example #12
Source File: DefaultTokenGetter.java From t-io with Apache License 2.0 | 5 votes |
@Override public String getToken(HttpRequest request) { // HttpSession httpSession = request.getHttpSession(); // if (httpSession != null) { // return httpSession.getId(); // } // Cookie cookie = DefaultHttpRequestHandler.getSessionCookie(request, request.httpConfig); // if (cookie != null) { // log.error("token from cookie: {}", cookie.getValue()); // return cookie.getValue(); // } return DefaultHttpRequestHandler.getSessionId(request); }
Example #13
Source File: HttpServerAioHandler.java From t-io with Apache License 2.0 | 5 votes |
@Override public HttpRequest decode(ByteBuffer buffer, int limit, int position, int readableLength, ChannelContext channelContext) throws AioDecodeException { HttpRequest request = HttpRequestDecoder.decode(buffer, limit, position, readableLength, channelContext, httpConfig); if (request != null) { channelContext.setAttribute(REQUEST_KEY, request); } return request; }
Example #14
Source File: Resps.java From t-io with Apache License 2.0 | 5 votes |
/** * 根据byte[]创建响应 * @param request * @param bodyBytes * @param extension 后缀,可以为空 * @return * @author tanyaowu */ public static HttpResponse bytes(HttpRequest request, byte[] bodyBytes, String extension) { String contentType = null; // String extension = FilenameUtils.getExtension(filename); if (StrUtil.isNotBlank(extension)) { MimeType mimeType = MimeType.fromExtension(extension); if (mimeType != null) { contentType = mimeType.getType(); } else { contentType = "application/octet-stream"; } } return bytesWithContentType(request, bodyBytes, contentType); }
Example #15
Source File: DefaultHttpRequestHandler.java From t-io with Apache License 2.0 | 5 votes |
/** * 检查域名是否可以访问本站 * @param request * @return * @author tanyaowu */ private boolean checkDomain(HttpRequest request) { String[] allowDomains = httpConfig.getAllowDomains(); if (allowDomains == null || allowDomains.length == 0) { return true; } String host = request.getHost(); if (ArrayUtil.contains(allowDomains, host)) { return true; } return false; }
Example #16
Source File: Resps.java From t-io with Apache License 2.0 | 5 votes |
/** * * @param request * @param bodyBytes * @param contentType 形如:application/octet-stream等 * @return * @author tanyaowu */ public static HttpResponse bytesWithContentType(HttpRequest request, byte[] bodyBytes, String contentType) { HttpResponse ret = new HttpResponse(request); ret.setBody(bodyBytes); if (StrUtil.isBlank(contentType)) { ret.addHeader(HeaderName.Content_Type, HeaderValue.Content_Type.DEFAULT_TYPE); } else { ret.addHeader(HeaderName.Content_Type, HeaderValue.Content_Type.from(contentType)); } return ret; }
Example #17
Source File: Resps.java From t-io with Apache License 2.0 | 5 votes |
/** * Content-Type: application/json;charset=utf-8 * @param request * @param body * @param charset * @return * @author tanyaowu */ public static HttpResponse json(HttpRequest request, Object body, String charset) { HttpResponse ret = null; if (body == null) { ret = string(request, "", charset, getMimeTypeStr(MimeType.TEXT_PLAIN_JSON, charset)); } else { if (body.getClass() == String.class || ClassUtil.isBasicType(body.getClass())) { ret = string(request, body + "", charset, getMimeTypeStr(MimeType.TEXT_PLAIN_JSON, charset)); } else { ret = string(request, Json.toJson(body), charset, getMimeTypeStr(MimeType.TEXT_PLAIN_JSON, charset)); } } return ret; }
Example #18
Source File: WsServerAioHandler.java From t-io with Apache License 2.0 | 5 votes |
/** * 本方法改编自baseio: https://gitee.com/generallycloud/baseio<br> * 感谢开源作者的付出 * * @param request * @param channelContext * @return * @author tanyaowu */ public static HttpResponse updateWebSocketProtocol(HttpRequest request, ChannelContext channelContext) { Map<String, String> headers = request.getHeaders(); String Sec_WebSocket_Key = headers.get(HttpConst.RequestHeaderKey.Sec_WebSocket_Key); if (StrUtil.isNotBlank(Sec_WebSocket_Key)) { byte[] Sec_WebSocket_Key_Bytes = null; try { Sec_WebSocket_Key_Bytes = Sec_WebSocket_Key.getBytes(request.getCharset()); } catch (UnsupportedEncodingException e) { // log.error(e.toString(), e); throw new RuntimeException(e); } byte[] allBs = new byte[Sec_WebSocket_Key_Bytes.length + SEC_WEBSOCKET_KEY_SUFFIX_BYTES.length]; System.arraycopy(Sec_WebSocket_Key_Bytes, 0, allBs, 0, Sec_WebSocket_Key_Bytes.length); System.arraycopy(SEC_WEBSOCKET_KEY_SUFFIX_BYTES, 0, allBs, Sec_WebSocket_Key_Bytes.length, SEC_WEBSOCKET_KEY_SUFFIX_BYTES.length); // String Sec_WebSocket_Key_Magic = Sec_WebSocket_Key + SEC_WEBSOCKET_KEY_SUFFIX_BYTES; byte[] key_array = SHA1Util.SHA1(allBs); String acceptKey = BASE64Util.byteArrayToBase64(key_array); HttpResponse httpResponse = new HttpResponse(request); httpResponse.setStatus(HttpResponseStatus.C101); Map<HeaderName, HeaderValue> respHeaders = new HashMap<>(); respHeaders.put(HeaderName.Connection, HeaderValue.Connection.Upgrade); respHeaders.put(HeaderName.Upgrade, HeaderValue.Upgrade.WebSocket); respHeaders.put(HeaderName.Sec_WebSocket_Accept, HeaderValue.from(acceptKey)); httpResponse.addHeaders(respHeaders); return httpResponse; } return null; }
Example #19
Source File: Resps.java From t-io with Apache License 2.0 | 5 votes |
/** * 用页面重定向 * @param request * @param path * @return * @author tanyaowu */ public static HttpResponse redirectWithPage(HttpRequest request, String path) { StringBuilder sb = new StringBuilder(256); sb.append("<script>"); sb.append("window.location.href='").append(path).append("'"); sb.append("</script>"); return Resps.html(request, sb.toString()); }
Example #20
Source File: TestController.java From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License | 5 votes |
@RequestPath(value = "plaintext") public HttpResponse plaintext(HttpRequest request) throws Exception { //更高性能的写法 HttpResponse ret = new HttpResponse(request); ret.setBody(HELLO_WORLD_BYTES); ret.addHeader(HeaderName.Content_Type, HeaderValue.Content_Type.TEXT_PLAIN_TXT); return ret; //简便写法 // return Resps.bytesWithContentType(request, HELLO_WORLD_BYTES, MimeType.TEXT_PLAIN_TXT.getType()); }
Example #21
Source File: IpUtils.java From t-io with Apache License 2.0 | 5 votes |
/** * * @param request * @return * @author tanyaowu */ public static String getRealIp(HttpRequest request) { // return getRealIp(request.channelContext, request.httpConfig, request.getHeaders()); if (request.httpConfig == null) { return request.getRemote().getIp(); } if (request.httpConfig.isProxied()) { String headerName = null; String ip = null; for (String name : HEADER_NAMES_FOR_REALIP) { headerName = name; ip = request.getHeader(headerName); if (StrUtil.isNotBlank(ip) && !"unknown".equalsIgnoreCase(ip)) { break; } } if (StrUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { headerName = null; ip = request.getRemote().getIp(); } if (ip.contains(",")) { log.error("ip[{}], header name:{}", ip, headerName); ip = ip.split(",")[0].trim(); } return ip; } else { return request.getRemote().getIp(); } }
Example #22
Source File: Routes.java From t-io with Apache License 2.0 | 5 votes |
@SuppressWarnings("unused") public Method getMethodByPath(String path, HttpRequest request) { Method method = PATH_METHOD_MAP.get(path); if (method == null) { String[] pathUnitsOfRequest = StrUtil.split(path, "/"); // "/user/214" -- > ["user", "214"] VariablePathVo[] variablePathVos = VARIABLE_PATH_MAP.get(pathUnitsOfRequest.length); if (variablePathVos != null) { tag1: for (VariablePathVo variablePathVo : variablePathVos) { PathUnitVo[] pathUnitVos = variablePathVo.getPathUnits(); tag2: for (int i = 0; i < pathUnitVos.length; i++) { PathUnitVo pathUnitVo = pathUnitVos[i]; String pathUnitOfRequest = pathUnitsOfRequest[i]; if (pathUnitVo.isVar()) { request.addParam(pathUnitVo.getPath(), pathUnitOfRequest); } else { if (!StrUtil.equals(pathUnitVo.getPath(), pathUnitOfRequest)) { continue tag1; } } } String metapath = variablePathVo.getPath(); String forward = PATH_FORWARD_MAP.get(metapath); if (StrUtil.isNotBlank(forward)) { request.requestLine.path = forward; } method = variablePathVo.getMethod(); return method; } } return null; } else { return method; } }
Example #23
Source File: DefaultHttpRequestHandler.java From t-io with Apache License 2.0 | 5 votes |
/** * 创建httpsession * @return * @author tanyaowu */ public HttpSession createSession(HttpRequest request) { String sessionId = httpConfig.getSessionIdGenerator().sessionId(httpConfig, request); HttpSession httpSession = new HttpSession(sessionId); if (httpSessionListener != null) { httpSessionListener.doAfterCreated(request, httpSession, httpConfig); } return httpSession; }
Example #24
Source File: DefaultHttpRequestHandler.java From t-io with Apache License 2.0 | 5 votes |
public static String getSessionId(HttpRequest request) { String sessionId = request.getString(org.tio.http.common.HttpConfig.TIO_HTTP_SESSIONID); if (StrUtil.isNotBlank(sessionId)) { return sessionId; } Cookie cookie = getSessionCookie(request, request.httpConfig); if (cookie != null) { return cookie.getValue(); } return null; }
Example #25
Source File: FileCache.java From t-io with Apache License 2.0 | 5 votes |
public HttpResponse cloneResponse(HttpRequest request) { // HttpResponse responseInCache = fileCache.getResponse(); HttpResponse ret = new HttpResponse(request); ret.setBody(response.getBody()); ret.setHasGzipped(response.isHasGzipped()); ret.addHeaders(response.getHeaders()); return ret; }
Example #26
Source File: TestController.java From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License | 5 votes |
@RequestPath(value = "json") public HttpResponse json(HttpRequest request) throws Exception { //更高性能的写法 HttpResponse ret = new HttpResponse(request); ret.setBody(Json.toJson(new Message(HELLO_WORLD)).getBytes()); ret.addHeader(HeaderName.Content_Type, HeaderValue.Content_Type.TEXT_PLAIN_JSON); return ret; //简便写法 // return Resps.json(request, new Message(HELLO_WORLD)); }
Example #27
Source File: DefaultHttpRequestHandler.java From t-io with Apache License 2.0 | 5 votes |
public static String getDomain(HttpRequest request) { String domain = request.getDomain(); boolean isip = Validator.isIpv4(domain); if (!isip) { String[] dms = StrUtil.split(domain, "."); if (dms.length > 2) { domain = "." + dms[dms.length - 2] + "." + dms[dms.length - 1]; } } return domain; }
Example #28
Source File: DefaultHttpRequestHandler.java From t-io with Apache License 2.0 | 5 votes |
/** * 根据session创建session对应的cookie * 注意:先有session,后有session对应的cookie * @param request * @param httpSession * @param httpResponse * @param forceCreate * @return * @author tanyaowu */ private void createSessionCookie(HttpRequest request, HttpSession httpSession, HttpResponse httpResponse, boolean forceCreate) { if (httpResponse == null) { return; } if (!forceCreate) { Object test = request.channelContext.getAttribute(SESSION_COOKIE_KEY); if (test != null) { return; } } String sessionId = httpSession.getId(); String domain = getDomain(request); String name = httpConfig.getSessionCookieName(); long maxAge = 3600 * 24 * 365 * 10;//Math.max(httpConfig.getSessionTimeout() * 30, 3600 * 24 * 365 * 10); Cookie sessionCookie = new Cookie(domain, name, sessionId, maxAge); if (sessionCookieDecorator != null) { sessionCookieDecorator.decorate(sessionCookie, request, request.getDomain()); } httpResponse.addCookie(sessionCookie); httpConfig.getSessionStore().put(sessionId, httpSession); request.channelContext.setAttribute(SESSION_COOKIE_KEY, sessionCookie); return; }
Example #29
Source File: DefaultHttpRequestHandler.java From t-io with Apache License 2.0 | 5 votes |
/** * 更新sessionId * @param request * @param httpSession * @param httpResponse * @return * @author tanyaowu */ public HttpSession updateSessionId(HttpRequest request, HttpSession httpSession, HttpResponse httpResponse) { String oldId = httpSession.getId(); String newId = httpConfig.getSessionIdGenerator().sessionId(httpConfig, request); httpSession.setId(newId); if (httpSessionListener != null) { httpSessionListener.doAfterCreated(request, httpSession, httpConfig); } httpConfig.getSessionStore().remove(oldId); createSessionCookie(request, httpSession, httpResponse, true); httpSession.update(httpConfig); //HttpSession有变动时,都要调一下update() return httpSession; }
Example #30
Source File: DispatcheHttpRequestHandler.java From t-io with Apache License 2.0 | 4 votes |
@Override public HttpResponse resp404(HttpRequest request, RequestLine requestLine) throws Exception { HttpRequestHandler httpRequestHandler = _getHttpRequestHandler(request); return httpRequestHandler.resp404(request, requestLine); }