Java Code Examples for io.netty.handler.codec.http.HttpHeaders#get()

The following examples show how to use io.netty.handler.codec.http.HttpHeaders#get() . 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: MultiPartParserDefinition.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public void beginPart(final HttpHeaders headers) {
    this.currentFileSize = 0;
    this.headers = headers;
    final String disposition = headers.get(HttpHeaderNames.CONTENT_DISPOSITION);
    if (disposition != null) {
        if (disposition.startsWith("form-data")) {
            currentName = HttpHeaderNames.extractQuotedValueFromHeader(disposition, "name");
            fileName = HttpHeaderNames.extractQuotedValueFromHeaderWithEncoding(disposition, "filename");
            if (fileName != null && fileSizeThreshold == 0) {
                try {
                    if (tempFileLocation != null) {
                        file = Files.createTempFile(tempFileLocation, "undertow", "upload");
                    } else {
                        file = Files.createTempFile("undertow", "upload");
                    }
                    createdFiles.add(file);
                    fileChannel = FileChannel.open(file, StandardOpenOption.READ, StandardOpenOption.WRITE);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
 
Example 2
Source File: FrontendIntegrationTest.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies blob properties from output, to that sent in during input
 * @param expectedHeaders the expected headers in the response.
 * @param isPrivate {@code true} if the blob is expected to be private
 * @param response the {@link HttpResponse} that contains the headers.
 */
private void verifyBlobProperties(HttpHeaders expectedHeaders, boolean isPrivate, HttpResponse response) {
  assertEquals("Blob size does not match", Long.parseLong(expectedHeaders.get(RestUtils.Headers.BLOB_SIZE)),
      Long.parseLong(response.headers().get(RestUtils.Headers.BLOB_SIZE)));
  assertEquals(RestUtils.Headers.SERVICE_ID + " does not match", expectedHeaders.get(RestUtils.Headers.SERVICE_ID),
      response.headers().get(RestUtils.Headers.SERVICE_ID));
  assertEquals(RestUtils.Headers.PRIVATE + " does not match", isPrivate,
      Boolean.valueOf(response.headers().get(RestUtils.Headers.PRIVATE)));
  assertEquals(RestUtils.Headers.AMBRY_CONTENT_TYPE + " does not match",
      expectedHeaders.get(RestUtils.Headers.AMBRY_CONTENT_TYPE),
      response.headers().get(RestUtils.Headers.AMBRY_CONTENT_TYPE));
  assertTrue("No " + RestUtils.Headers.CREATION_TIME,
      response.headers().get(RestUtils.Headers.CREATION_TIME, null) != null);
  if (expectedHeaders.get(RestUtils.Headers.TTL) != null
      && Long.parseLong(expectedHeaders.get(RestUtils.Headers.TTL)) != Utils.Infinite_Time) {
    assertEquals(RestUtils.Headers.TTL + " does not match", expectedHeaders.get(RestUtils.Headers.TTL),
        response.headers().get(RestUtils.Headers.TTL));
  } else {
    assertFalse("There should be no TTL in the response", response.headers().contains(RestUtils.Headers.TTL));
  }
  if (expectedHeaders.contains(RestUtils.Headers.OWNER_ID)) {
    assertEquals(RestUtils.Headers.OWNER_ID + " does not match", expectedHeaders.get(RestUtils.Headers.OWNER_ID),
        response.headers().get(RestUtils.Headers.OWNER_ID));
  }
}
 
Example 3
Source File: HttpDownUtil.java    From proxyee-down with Apache License 2.0 6 votes vote down vote up
/**
 * 取当前请求的ContentLength
 */
public static long getDownContentSize(HttpHeaders resHeaders) {
  String contentRange = resHeaders.get(HttpHeaderNames.CONTENT_RANGE);
  if (contentRange != null) {
    Pattern pattern = Pattern.compile("^[^\\d]*(\\d+)-(\\d+)/.*$");
    Matcher matcher = pattern.matcher(contentRange);
    if (matcher.find()) {
      long startSize = Long.parseLong(matcher.group(1));
      long endSize = Long.parseLong(matcher.group(2));
      return endSize - startSize + 1;
    }
  } else {
    String contentLength = resHeaders.get(HttpHeaderNames.CONTENT_LENGTH);
    if (contentLength != null) {
      return Long.valueOf(resHeaders.get(HttpHeaderNames.CONTENT_LENGTH));
    }
  }
  return 0;
}
 
Example 4
Source File: WebSocketClientHandshaker13.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Process server response:
 * </p>
 *
 * <pre>
 * HTTP/1.1 101 Switching Protocols
 * Upgrade: websocket
 * Connection: Upgrade
 * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
 * Sec-WebSocket-Protocol: chat
 * </pre>
 *
 * @param response
 *            HTTP response returned from the server for the request sent by beginOpeningHandshake00().
 * @throws WebSocketHandshakeException
 */
@Override
protected void verify(FullHttpResponse response) {
    final HttpResponseStatus status = HttpResponseStatus.SWITCHING_PROTOCOLS;
    final HttpHeaders headers = response.headers();

    if (!response.getStatus().equals(status)) {
        throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.getStatus());
    }

    String upgrade = headers.get(Names.UPGRADE);
    if (!Values.WEBSOCKET.equalsIgnoreCase(upgrade)) {
        throw new WebSocketHandshakeException("Invalid handshake response upgrade: " + upgrade);
    }

    String connection = headers.get(Names.CONNECTION);
    if (!Values.UPGRADE.equalsIgnoreCase(connection)) {
        throw new WebSocketHandshakeException("Invalid handshake response connection: " + connection);
    }

    String accept = headers.get(Names.SEC_WEBSOCKET_ACCEPT);
    if (accept == null || !accept.equals(expectedChallengeResponseString)) {
        throw new WebSocketHandshakeException(String.format(
                "Invalid challenge. Actual: %s. Expected: %s", accept, expectedChallengeResponseString));
    }
}
 
Example 5
Source File: HttpDownUtil.java    From pdown-core with MIT License 6 votes vote down vote up
/**
 * 取请求下载文件的总大小
 */
public static long getDownFileSize(HttpHeaders resHeaders) {
  String contentRange = resHeaders.get(HttpHeaderNames.CONTENT_RANGE);
  if (contentRange != null) {
    Pattern pattern = Pattern.compile("^.*/(\\d+).*$");
    Matcher matcher = pattern.matcher(contentRange);
    if (matcher.find()) {
      return Long.parseLong(matcher.group(1));
    }
  } else {
    String contentLength = resHeaders.get(HttpHeaderNames.CONTENT_LENGTH);
    if (contentLength != null) {
      return Long.valueOf(resHeaders.get(HttpHeaderNames.CONTENT_LENGTH));
    }
  }
  return 0;
}
 
Example 6
Source File: WebSocketClientHandshaker07.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Process server response:
 * </p>
 *
 * <pre>
 * HTTP/1.1 101 Switching Protocols
 * Upgrade: websocket
 * Connection: Upgrade
 * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
 * Sec-WebSocket-Protocol: chat
 * </pre>
 *
 * @param response
 *            HTTP response returned from the server for the request sent by beginOpeningHandshake00().
 * @throws WebSocketHandshakeException
 */
@Override
protected void verify(FullHttpResponse response) {
    final HttpResponseStatus status = HttpResponseStatus.SWITCHING_PROTOCOLS;
    final HttpHeaders headers = response.headers();

    if (!response.getStatus().equals(status)) {
        throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.getStatus());
    }

    String upgrade = headers.get(Names.UPGRADE);
    if (!Values.WEBSOCKET.equalsIgnoreCase(upgrade)) {
        throw new WebSocketHandshakeException("Invalid handshake response upgrade: " + upgrade);
    }

    String connection = headers.get(Names.CONNECTION);
    if (!Values.UPGRADE.equalsIgnoreCase(connection)) {
        throw new WebSocketHandshakeException("Invalid handshake response connection: " + connection);
    }

    String accept = headers.get(Names.SEC_WEBSOCKET_ACCEPT);
    if (accept == null || !accept.equals(expectedChallengeResponseString)) {
        throw new WebSocketHandshakeException(String.format(
                "Invalid challenge. Actual: %s. Expected: %s", accept, expectedChallengeResponseString));
    }
}
 
Example 7
Source File: HttpDownUtil.java    From proxyee-down with Apache License 2.0 6 votes vote down vote up
/**
 * 取请求下载文件的总大小
 */
public static long getDownFileSize(HttpHeaders resHeaders) {
  String contentRange = resHeaders.get(HttpHeaderNames.CONTENT_RANGE);
  if (contentRange != null) {
    Pattern pattern = Pattern.compile("^.*/(\\d+).*$");
    Matcher matcher = pattern.matcher(contentRange);
    if (matcher.find()) {
      return Long.parseLong(matcher.group(1));
    }
  } else {
    String contentLength = resHeaders.get(HttpHeaderNames.CONTENT_LENGTH);
    if (contentLength != null) {
      return Long.valueOf(resHeaders.get(HttpHeaderNames.CONTENT_LENGTH));
    }
  }
  return 0;
}
 
Example 8
Source File: HttpConversionUtil.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private static void setHttp2Scheme(HttpHeaders in, URI uri, Http2Headers out) {
    String value = uri.getScheme();
    if (value != null) {
        out.scheme(new AsciiString(value));
        return;
    }

    // Consume the Scheme extension header if present
    CharSequence cValue = in.get(ExtensionHeaderNames.SCHEME.text());
    if (cValue != null) {
        out.scheme(AsciiString.of(cValue));
        return;
    }

    if (uri.getPort() == HTTPS.port()) {
        out.scheme(HTTPS.name());
    } else if (uri.getPort() == HTTP.port()) {
        out.scheme(HTTP.name());
    } else {
        throw new IllegalArgumentException(":scheme must be specified. " +
                "see https://tools.ietf.org/html/rfc7540#section-8.1.2.3");
    }
}
 
Example 9
Source File: DFHttpSyncHandler.java    From dfactor with MIT License 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
	try{
		if(msg instanceof FullHttpResponse){
			FullHttpResponse rsp = (FullHttpResponse) msg;
			HttpHeaders headers = rsp.headers();
			long contentLen = HttpUtil.getContentLength(rsp);
			String contentType = headers.get(HttpHeaderNames.CONTENT_TYPE);
			//
			DFHttpCliRsp dfRsp = null;
			ByteBuf buf = rsp.content();
			//parse msg
			boolean isString = contentIsString(contentType);
			if(isString){  //String
				String str = null;
				if(buf != null){
					str = (String) buf.readCharSequence(buf.readableBytes(), CharsetUtil.UTF_8);
				}
				dfRsp = new DFHttpCliRspWrap(rsp.status().code(), headers,
						contentType, (int) contentLen, 
						null, str);
			}else{  //binary
				dfRsp = new DFHttpCliRspWrap(rsp.status().code(), headers,
						contentType, (int) contentLen, 
						buf, null);
			}
			//
			_recvData = dfRsp;
			if(!isString && buf != null){
       			buf.retain();
       		}
		}
	}finally{
		if(_recvPromise != null){
			_recvPromise.setSuccess();
		}
		ReferenceCountUtil.release(msg);
	}
}
 
Example 10
Source File: NettyHttpUtil.java    From netty-cookbook with Apache License 2.0 5 votes vote down vote up
public static String getRefererUrl(HttpHeaders headers){
	String refererUrl = headers.get(REFERER);
	if(StringUtil.isNotEmpty(refererUrl)){
		refererUrl = StringUtils.replaceEach(refererUrl, REFERER_SEARCH_LIST,  REFERER_REPLACE_LIST);
	}
	return refererUrl;
}
 
Example 11
Source File: MainAndStaticFileHandler.java    From crate with Apache License 2.0 5 votes vote down vote up
private CompletableFuture<FullHttpResponse> serveJsonOrSite(FullHttpRequest request, ByteBufAllocator alloc) throws IOException {
    HttpHeaders headers = request.headers();
    String userAgent = headers.get(HttpHeaderNames.USER_AGENT);
    String accept = headers.get(HttpHeaderNames.ACCEPT);
    if (shouldServeJSON(userAgent, accept, request.uri())) {
        return serveJSON(request.method(), alloc);
    } else {
        return completedFuture(StaticSite.serveSite(sitePath, request, alloc));
    }
}
 
Example 12
Source File: OuterMsgId.java    From xian with Apache License 2.0 5 votes vote down vote up
/**
 * 从httpRequest的Header内摘取出msgId,处于安全考虑,我们只摘取standalone节点传入的msgId <br>
 * 如果取不到那么返回null
 */
public static String get(FullHttpRequest fullHttpRequest) {
    HttpHeaders httpHeaders = fullHttpRequest.headers();
    if (isNodeLegal(httpHeaders) && !StringUtil.isEmpty(httpHeaders.get(Constant.XIAN_MSG_ID_HEADER))) {
        return httpHeaders.get(Constant.XIAN_MSG_ID_HEADER);
    }
    return null;
}
 
Example 13
Source File: RpcxHttpHandler.java    From rpcx-java with Apache License 2.0 5 votes vote down vote up
private String getClientIp(ChannelHandlerContext ctx, FullHttpRequest request) {
    HttpHeaders httpHeaders = request.headers();
    String remoteIP = httpHeaders.get("X-Forwarded-For");
    if (remoteIP == null) {
        remoteIP = httpHeaders.get("X-Real-IP");
    }
    if (remoteIP != null) {
        return remoteIP;
    } else { // request取不到就从channel里取
        return ((InetSocketAddress) ctx.channel().remoteAddress()).getHostName();
    }
}
 
Example 14
Source File: ClientToProxyConnection.java    From g4proxy with Apache License 2.0 5 votes vote down vote up
/**
 * Switch the de-facto standard "Proxy-Connection" header to "Connection"
 * when we pass it along to the remote host. This is largely undocumented
 * but seems to be what most browsers and servers expect.
 * 
 * @param headers
 *            The headers to modify
 */
private void switchProxyConnectionHeader(HttpHeaders headers) {
    String proxyConnectionKey = "Proxy-Connection";
    if (headers.contains(proxyConnectionKey)) {
        String header = headers.get(proxyConnectionKey);
        headers.remove(proxyConnectionKey);
        headers.set(HttpHeaders.Names.CONNECTION, header);
    }
}
 
Example 15
Source File: EtcdKeysResponse.java    From etcd4j with Apache License 2.0 5 votes vote down vote up
@Override
public void loadHeaders(HttpHeaders headers) {
  if(headers != null) {
    this.etcdClusterId = headers.get("X-Etcd-Cluster-Id");
    this.etcdIndex = getHeaderPropertyAsLong(headers, "X-Etcd-Index");
    this.raftIndex = getHeaderPropertyAsLong(headers, "X-Raft-Index");
    this.raftTerm = getHeaderPropertyAsLong(headers, "X-Raft-Term");
  }
}
 
Example 16
Source File: NettyHttpUtil.java    From netty-cookbook with Apache License 2.0 5 votes vote down vote up
public static String getRefererUrl(HttpHeaders headers){
	String refererUrl = headers.get(REFERER);
	if(StringUtil.isNotEmpty(refererUrl)){
		refererUrl = StringUtils.replaceEach(refererUrl, REFERER_SEARCH_LIST,  REFERER_REPLACE_LIST);
	}
	return refererUrl;
}
 
Example 17
Source File: WebSocketClientHandshaker00.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * Process server response:
 * </p>
 *
 * <pre>
 * HTTP/1.1 101 WebSocket Protocol Handshake
 * Upgrade: WebSocket
 * Connection: Upgrade
 * Sec-WebSocket-Origin: http://example.com
 * Sec-WebSocket-Location: ws://example.com/demo
 * Sec-WebSocket-Protocol: sample
 *
 * 8jKS'y:G*Co,Wxa-
 * </pre>
 *
 * @param response
 *            HTTP response returned from the server for the request sent by beginOpeningHandshake00().
 * @throws WebSocketHandshakeException
 */
@Override
protected void verify(FullHttpResponse response) {
    final HttpResponseStatus status = new HttpResponseStatus(101, "WebSocket Protocol Handshake");

    if (!response.getStatus().equals(status)) {
        throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.getStatus());
    }

    HttpHeaders headers = response.headers();

    String upgrade = headers.get(Names.UPGRADE);
    if (!Values.WEBSOCKET.equalsIgnoreCase(upgrade)) {
        throw new WebSocketHandshakeException("Invalid handshake response upgrade: "
                + upgrade);
    }

    String connection = headers.get(Names.CONNECTION);
    if (!Values.UPGRADE.equalsIgnoreCase(connection)) {
        throw new WebSocketHandshakeException("Invalid handshake response connection: "
                + connection);
    }

    ByteBuf challenge = response.content();
    if (!challenge.equals(expectedChallengeResponseBytes)) {
        throw new WebSocketHandshakeException("Invalid challenge");
    }
}
 
Example 18
Source File: HttpRequestAdaptor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
public String getHeader(HttpServerRequest request, String name) {
    try {
        final HttpHeaders headers = request.requestHeaders();
        if (headers != null) {
            return headers.get(name);
        }
    } catch (Exception ignored) {
    }
    return null;
}
 
Example 19
Source File: HttpDownSniffIntercept.java    From proxyee-down with Apache License 2.0 5 votes vote down vote up
@Override
public void afterResponse(Channel clientChannel, Channel proxyChannel, HttpResponse httpResponse,
    HttpProxyInterceptPipeline pipeline) throws Exception {
  if ((httpResponse.status().code() + "").indexOf("20") == 0) { //响应码为20x
    HttpHeaders httpResHeaders = httpResponse.headers();
    String accept = pipeline.getHttpRequest().headers().get(HttpHeaderNames.ACCEPT);
    String contentType = httpResHeaders.get(HttpHeaderNames.CONTENT_TYPE);
    //有两种情况进行下载 1.url后缀为.xxx  2.带有CONTENT_DISPOSITION:ATTACHMENT响应头
    String disposition = httpResHeaders.get(HttpHeaderNames.CONTENT_DISPOSITION);
    if ((disposition != null
        && accept != null
        && !accept.equals("*/*")
        && disposition.contains(HttpHeaderValues.ATTACHMENT)
        && disposition.contains(HttpHeaderValues.FILENAME))
        || (!pipeline.getHttpRequest().uri().matches("^.*/favicon\\.ico(\\?[^?]*)?$")
        && pipeline.getHttpRequest().uri().matches("^.*\\.[^./]{1,5}(\\?[^?]*)?$")
        && isDownAccept(accept, contentType))) {
      downFlag = true;
    }

    HttpRequestInfo httpRequestInfo = (HttpRequestInfo) pipeline.getHttpRequest();
    if (downFlag) {   //如果是下载
      proxyChannel.close();//关闭嗅探下载连接
      LOGGER.debug("=====================下载===========================\n" +
          pipeline.getHttpRequest().toString() + "\n" +
          "------------------------------------------------" +
          httpResponse.toString() + "\n" +
          "================================================");
      //原始的请求协议
      httpRequestInfo.setRequestProto(pipeline.getRequestProto());
      pipeline.afterResponse(clientChannel, proxyChannel, httpResponse);
    } else {
      if (httpRequestInfo.content() != null) {
        httpRequestInfo.setContent(null);
      }
    }
  }
  pipeline.getDefault().afterResponse(clientChannel, proxyChannel, httpResponse, pipeline);
}
 
Example 20
Source File: UKTools.java    From youkefu with Apache License 2.0 5 votes vote down vote up
public static String getIpAddr(HttpHeaders headers , String remoteAddr) {  
    String ip = headers.get("x-forwarded-for");  
    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
        ip = headers.get("Proxy-Client-IP");  
    }  
    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
        ip = headers.get("WL-Proxy-Client-IP");  
    }  
    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
        ip = remoteAddr;  
    }  
    return ip;  
}