org.tio.http.common.HttpResponse Java Examples

The following examples show how to use org.tio.http.common.HttpResponse. 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: HttpGzipUtils.java    From t-io with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param response
 * @author tanyaowu
 */
public static void gzip(HttpResponse response) {
	if (response == null) {
		return;
	}

	// 已经gzip过了,就不必再压缩了
	if (response.isHasGzipped()) {
		return;
	}

	byte[] bs = response.getBody();
	if (bs != null && bs.length >= 300) {
		byte[] bs2 = ZipUtil.gzip(bs);
		if (bs2.length < bs.length) {
			response.setBody(bs2);
			response.setHasGzipped(true);
			response.addHeader(HeaderName.Content_Encoding, HeaderValue.Content_Encoding.gzip);
		}
	}
}
 
Example #2
Source File: HttpGzipUtils.java    From t-io with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @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 #3
Source File: Resps.java    From t-io with Apache License 2.0 6 votes vote down vote up
/**
 * 尝试返回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 #4
Source File: Resps.java    From t-io with Apache License 2.0 6 votes vote down vote up
/**
	 * 创建字符串输出
	 * @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 #5
Source File: WsServerAioHandler.java    From t-io with Apache License 2.0 6 votes vote down vote up
@Override
public ByteBuffer encode(Packet packet, TioConfig tioConfig, ChannelContext channelContext) {
	WsResponse wsResponse = (WsResponse) packet;

	// 握手包
	if (wsResponse.isHandShake()) {
		WsSessionContext imSessionContext = (WsSessionContext) channelContext.get();
		HttpResponse handshakeResponse = imSessionContext.getHandshakeResponse();
		try {
			return HttpResponseEncoder.encode(handshakeResponse, tioConfig, channelContext);
		} catch (UnsupportedEncodingException e) {
			log.error(e.toString(), e);
			return null;
		}
	}

	ByteBuffer byteBuffer = WsServerEncoder.encode(wsResponse, tioConfig, channelContext);
	return byteBuffer;
}
 
Example #6
Source File: DefaultHttpRequestHandler.java    From t-io with Apache License 2.0 6 votes vote down vote up
@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 #7
Source File: Resps.java    From t-io with Apache License 2.0 6 votes vote down vote up
/**
 * 根据文件创建响应
 * @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 #8
Source File: DefaultHttpRequestHandler.java    From t-io with Apache License 2.0 6 votes vote down vote up
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 #9
Source File: TestController.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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 #10
Source File: FileCache.java    From t-io with Apache License 2.0 5 votes vote down vote up
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 #11
Source File: FileCache.java    From t-io with Apache License 2.0 5 votes vote down vote up
public FileCache(HttpResponse response, long lastModified) {
	super();
	this.response = response;
	//		this.setHeaders(headers);
	this.lastModified = lastModified;
	//		this.data = data;
}
 
Example #12
Source File: DefaultHttpRequestHandler.java    From t-io with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse resp404(HttpRequest request, RequestLine requestLine) throws Exception {
	if (routes != null) {
		String page404 = httpConfig.getPage404();
		Method method = routes.PATH_METHOD_MAP.get(page404);
		if (method != null) {
			return Resps.forward(request, page404);
		}
	}

	return Resps.resp404(request, requestLine, httpConfig);
}
 
Example #13
Source File: DefaultHttpRequestHandler.java    From t-io with Apache License 2.0 5 votes vote down vote up
/**
 * 更新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 #14
Source File: DefaultHttpRequestHandler.java    From t-io with Apache License 2.0 5 votes vote down vote up
/**
 * 根据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 #15
Source File: HttpServerAioHandler.java    From t-io with Apache License 2.0 5 votes vote down vote up
@Override
public ByteBuffer encode(Packet packet, TioConfig tioConfig, ChannelContext channelContext) {
	HttpResponse httpResponse = (HttpResponse) packet;
	ByteBuffer byteBuffer;
	try {
		byteBuffer = HttpResponseEncoder.encode(httpResponse, tioConfig, channelContext);
		return byteBuffer;
	} catch (UnsupportedEncodingException e) {
		log.error(e.toString(), e);
		return null;
	}
}
 
Example #16
Source File: HttpServerAioListener.java    From t-io with Apache License 2.0 5 votes vote down vote up
@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 #17
Source File: Resps.java    From t-io with Apache License 2.0 5 votes vote down vote up
/**
 * 根据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 #18
Source File: Resps.java    From t-io with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @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 #19
Source File: Resps.java    From t-io with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #20
Source File: Resps.java    From t-io with Apache License 2.0 5 votes vote down vote up
/**
 * 用页面重定向
 * @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 #21
Source File: WsServerAioHandler.java    From t-io with Apache License 2.0 5 votes vote down vote up
/**
	 * 本方法改编自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 #22
Source File: TestController.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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 #23
Source File: DefaultStatPathFilter.java    From t-io with Apache License 2.0 4 votes vote down vote up
@Override
public boolean filter(String path, HttpRequest request, HttpResponse response) {
	return true;
}
 
Example #24
Source File: DispatcheHttpRequestHandler.java    From t-io with Apache License 2.0 4 votes vote down vote up
@Override
public HttpResponse resp500(HttpRequest request, RequestLine requestLine, Throwable throwable) throws Exception {
	HttpRequestHandler httpRequestHandler = _getHttpRequestHandler(request);
	return httpRequestHandler.resp500(request, requestLine, throwable);
}
 
Example #25
Source File: DispatcheHttpRequestHandler.java    From t-io with Apache License 2.0 4 votes vote down vote up
@Override
public HttpResponse resp404(HttpRequest request, RequestLine requestLine) throws Exception {
	HttpRequestHandler httpRequestHandler = _getHttpRequestHandler(request);
	return httpRequestHandler.resp404(request, requestLine);
}
 
Example #26
Source File: SpringBootWsMsgHandler.java    From tio-starters with MIT License 4 votes vote down vote up
/**
 * 握手完毕
 * */
@Override
public void onAfterHandshaked(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {

}
 
Example #27
Source File: WebSocketImpl.java    From t-io with Apache License 2.0 4 votes vote down vote up
private void handshake() {
  readyState = WebSocket.CONNECTING;

  ClientChannelContext ctx = wsClient.getClientChannelContext();
  WsSessionContext session = (WsSessionContext) ctx.get();

  session.setHandshaked(false);

  String path = wsClient.uri.getPath();
  if (StrUtil.isBlank(path)) {
    path = "/";
  }
  ClientHttpRequest httpRequest =
      new ClientHttpRequest(Method.GET, path, wsClient.uri.getRawQuery());
  Map<String, String> headers = new HashMap<>();
  if (additionalHttpHeaders != null) headers.putAll(additionalHttpHeaders);
  headers.put("Host", wsClient.uri.getHost() + ":" + wsClient.uri.getPort());
  headers.put("Upgrade", "websocket");
  headers.put("Connection", "Upgrade");
  headers.put("Sec-WebSocket-Key", getSecWebsocketKey());
  headers.put("Sec-WebSocket-Version", "13");
  httpRequest.setHeaders(headers);

  session.setHandshakeRequest(httpRequest);

  ObjKit.Box<Disposable> disposableBox = ObjKit.box(null);

  disposableBox.value =
      publisher
          .filter(packet -> !session.isHandshaked())
          .subscribe(
              packet -> {
                if (packet instanceof HttpResponse) {
                  HttpResponse resp = (HttpResponse) packet;

                  if (resp.getStatus() == HttpResponseStatus.C101) {
                    HeaderValue upgrade = resp.getHeader(HeaderName.Upgrade);
                    if (upgrade == null || !upgrade.value.toLowerCase().equals("websocket")) {
                      close(1002, "no upgrade or upgrade invalid");
                      return;
                    }
                    HeaderValue connection = resp.getHeader(HeaderName.Connection);
                    if (connection == null || !connection.value.toLowerCase().equals("upgrade")) {
                      close(1002, "no connection or connection invalid");
                      return;
                    }
                    HeaderValue secWebsocketAccept =
                        resp.getHeader(HeaderName.Sec_WebSocket_Accept);
                    if (secWebsocketAccept == null
                        || !verifySecWebsocketAccept(secWebsocketAccept.value)) {
                      close(1002, "no Sec_WebSocket_Accept or Sec_WebSocket_Accept invalid");
                      return;
                    }
                    // TODO: Sec-WebSocket-Extensions, Sec-WebSocket-Protocol

                    readyState = WebSocket.OPEN;
                    session.setHandshaked(true);
                    onOpen();
                  } else {
                    // TODO: support other http code
                    close(1002, "not support http code: " + resp.getStatus().status);
                    return;
                  }

                  disposableBox.value.dispose();
                }
              });

  Tio.send(ctx, httpRequest);
}
 
Example #28
Source File: WsSessionContext.java    From t-io with Apache License 2.0 4 votes vote down vote up
/**
 * @param handshakeResponse the handshakeResponse to set
 */
public void setHandshakeResponse(HttpResponse handshakeResponse) {
	this.handshakeResponse = handshakeResponse;
}
 
Example #29
Source File: WsSessionContext.java    From t-io with Apache License 2.0 4 votes vote down vote up
/**
 * @return the handshakeResponse
 */
public HttpResponse getHandshakeResponse() {
	return handshakeResponse;
}
 
Example #30
Source File: FileCache.java    From t-io with Apache License 2.0 4 votes vote down vote up
public void setResponse(HttpResponse response) {
	this.response = response;
}