io.netty.handler.codec.http.HttpHeaders Java Examples

The following examples show how to use io.netty.handler.codec.http.HttpHeaders. 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: PublicAccessLogHandlerTest.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies either the expected request headers are found or not found (based on the parameter passed) in the
 * public access log entry
 * @param logEntry the public access log entry
 * @param headers expected headers
 * @param httpMethod HttpMethod type
 * @param expected, true if the headers are expected, false otherwise
 */
private void verifyPublicAccessLogEntryForRequestHeaders(String logEntry, HttpHeaders headers, HttpMethod httpMethod,
    boolean expected) {
  Iterator<Map.Entry<String, String>> itr = headers.iteratorAsString();
  while (itr.hasNext()) {
    Map.Entry<String, String> entry = itr.next();
    if (!entry.getKey().startsWith(NOT_LOGGED_HEADER_KEY) && !entry.getKey()
        .startsWith(EchoMethodHandler.RESPONSE_HEADER_KEY_PREFIX)) {
      if (httpMethod == HttpMethod.GET && !entry.getKey().equalsIgnoreCase(HttpHeaderNames.CONTENT_TYPE.toString())) {
        String subString = "[" + entry.getKey() + "=" + entry.getValue() + "]";
        boolean actual = logEntry.contains(subString);
        if (expected) {
          Assert.assertTrue("Public Access log entry does not have expected header " + entry.getKey(), actual);
        } else {
          Assert.assertFalse("Public Access log entry has unexpected header " + entry.getKey(), actual);
        }
      }
    }
  }
}
 
Example #2
Source File: HttpclientRequestHeadersInterceptor.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeMethod(final EnhancedInstance objInst,
                         final Method method,
                         final Object[] allArguments,
                         final Class<?>[] argumentsTypes,
                         final MethodInterceptResult result) throws Throwable {
    CarrierItem next = (CarrierItem) objInst.getSkyWalkingDynamicField();
    if (next != null) {
        HttpHeaders headers = (HttpHeaders) allArguments[0];
        while (next.hasNext()) {
            next = next.next();
            headers.remove(next.getHeadKey());
            headers.set(next.getHeadKey(), next.getHeadValue());
        }
    }
}
 
Example #3
Source File: ApiRequestParser.java    From netty.book.kor with MIT License 6 votes vote down vote up
private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) {
    // Decide whether to close the connection or not.
    boolean keepAlive = HttpHeaders.isKeepAlive(request);
    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
            currentObj.getDecoderResult().isSuccess() ? OK : BAD_REQUEST, Unpooled.copiedBuffer(
                    apiResult.toString(), CharsetUtil.UTF_8));

    response.headers().set(CONTENT_TYPE, "application/json; charset=UTF-8");

    if (keepAlive) {
        // Add 'Content-Length' header only for a keep-alive connection.
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
        // Add keep alive header as per:
        // -
        // http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // Write the response.
    ctx.write(response);

    return keepAlive;
}
 
Example #4
Source File: FallbackResponder.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public void sendResponse(FullHttpRequest req, ChannelHandlerContext ctx) throws Exception {
   counter.inc();
   byte[] content = null;

   try(InputStream is = FallbackResponder.class.getClassLoader().getResourceAsStream(resource)) {
      content = IOUtils.toByteArray(is);
   }

   FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
   HttpHeaders.setContentLength(response, content.length);
   response.headers().set(HttpHeaders.Names.CONTENT_TYPE, MediaType.APPLICATION_XML_UTF_8.toString());
   response.content().writeBytes(content);
   ctx.write(response);
   ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
   future.addListener(ChannelFutureListener.CLOSE);
}
 
Example #5
Source File: VerifyRequestSizeValidationComponentTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void should_return_bad_request_when_chunked_request_exceeds_endpoint_overridden_configured_max_request_size() throws Exception {
    NettyHttpClientRequestBuilder request = request()
        .withMethod(HttpMethod.POST)
        .withUri(BasicEndpointWithRequestSizeValidationOverride.MATCHING_PATH)
        .withPaylod(generatePayloadOfSizeInBytes(BasicEndpointWithRequestSizeValidationOverride.MAX_REQUEST_SIZE + 1))
        .withHeader(HttpHeaders.Names.TRANSFER_ENCODING, CHUNKED);

    // when
    NettyHttpClientResponse serverResponse = request.execute(serverConfig.endpointsPort(),
                                                            incompleteCallTimeoutMillis);

    // then
    assertThat(serverResponse.statusCode).isEqualTo(HttpResponseStatus.BAD_REQUEST.code());
    assertBadRequestErrorMessageAndMetadata(serverResponse.payload);
}
 
Example #6
Source File: NettyRequestTest.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link NettyRequest} with the given parameters.
 * @param httpMethod the {@link HttpMethod} desired.
 * @param uri the URI desired.
 * @param headers {@link HttpHeaders} that need to be a part of the request.
 * @param channel the {@link Channel} that the request arrived over.
 * @return {@link NettyRequest} encapsulating a {@link HttpRequest} with the given parameters.
 * @throws RestServiceException if the {@code httpMethod} is not recognized by {@link NettyRequest}.
 */
private NettyRequest createNettyRequest(HttpMethod httpMethod, String uri, HttpHeaders headers, Channel channel)
    throws RestServiceException {
  MetricRegistry metricRegistry = new MetricRegistry();
  RestRequestMetricsTracker.setDefaults(metricRegistry);
  HttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, httpMethod, uri, false);
  if (headers != null) {
    httpRequest.headers().set(headers);
  }
  NettyRequest nettyRequest =
      new NettyRequest(httpRequest, channel, new NettyMetrics(metricRegistry), BLACKLISTED_QUERY_PARAM_SET);
  assertEquals("Auto-read is in an invalid state",
      (!httpMethod.equals(HttpMethod.POST) && !httpMethod.equals(HttpMethod.PUT))
          || NettyRequest.bufferWatermark <= 0, channel.config().isAutoRead());
  return nettyRequest;
}
 
Example #7
Source File: FrontendIntegrationTest.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Method to easily create a request.
 * @param httpMethod the {@link HttpMethod} desired.
 * @param uri string representation of the desired URI.
 * @param headers any associated headers as a {@link HttpHeaders} object. Can be null.
 * @param content the content that accompanies the request. Can be null.
 * @return A {@link FullHttpRequest} object that defines the request required by the input.
 */
private FullHttpRequest buildRequest(HttpMethod httpMethod, String uri, HttpHeaders headers, ByteBuffer content) {
  ByteBuf contentBuf;
  if (content != null) {
    contentBuf = Unpooled.wrappedBuffer(content);
  } else {
    contentBuf = Unpooled.buffer(0);
  }
  FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, httpMethod, uri, contentBuf);
  if (headers != null) {
    httpRequest.headers().set(headers);
  }
  if (HttpMethod.POST.equals(httpMethod) && !HttpUtil.isContentLengthSet(httpRequest)) {
    HttpUtil.setTransferEncodingChunked(httpRequest, true);
  }
  return httpRequest;
}
 
Example #8
Source File: AbstractGenericHandler.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
/**
 * Add basic authentication headers to a {@link HttpRequest}.
 *
 * The given information is Base64 encoded and the authorization header is set appropriately. Since this needs
 * to be done for every request, it is refactored out.
 *
 * @param ctx the handler context.
 * @param request the request where the header should be added.
 * @param user the username for auth.
 * @param password the password for auth.
 */
public static void addHttpBasicAuth(final ChannelHandlerContext ctx, final HttpRequest request, final String user,
    final String password) {

    // if both user and password are null or empty, don't add http basic auth
    // this is usually the case when certificate auth is used.
    if ((user == null || user.isEmpty()) && (password == null || password.isEmpty())) {
        return;
    }

    final String pw = password == null ? "" : password;

    ByteBuf raw = ctx.alloc().buffer(user.length() + pw.length() + 1);
    raw.writeBytes((user + ":" + pw).getBytes(CHARSET));
    ByteBuf encoded = Base64.encode(raw, false);
    request.headers().add(HttpHeaders.Names.AUTHORIZATION, "Basic " + encoded.toString(CHARSET));
    encoded.release();
    raw.release();
}
 
Example #9
Source File: HttpPostRequestDecoderTest.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Test
public void testFilenameContainingSemicolon() throws Exception {
    final String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO";
    final DefaultFullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            "http://localhost");
    req.headers().add(HttpHeaders.Names.CONTENT_TYPE, "multipart/form-data; boundary=" + boundary);
    // Force to use memory-based data.
    final DefaultHttpDataFactory inMemoryFactory = new DefaultHttpDataFactory(false);
    final String data = "asdf";
    final String filename = "tmp;0.txt";
    final String body =
            "--" + boundary + "\r\n" +
                    "Content-Disposition: form-data; name=\"file\"; filename=\"" + filename + "\"\r\n" +
                    "Content-Type: image/gif\r\n" +
                    "\r\n" +
                    data + "\r\n" +
                    "--" + boundary + "--\r\n";

    req.content().writeBytes(body.getBytes(CharsetUtil.UTF_8.name()));
    // Create decoder instance to test.
    final HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(inMemoryFactory, req);
    assertFalse(decoder.getBodyHttpDatas().isEmpty());
    decoder.destroy();
}
 
Example #10
Source File: HttpUtil.java    From CapturePacket with MIT License 6 votes vote down vote up
/**
 * Retrieves the host and, optionally, the port from the specified request's Host header.
 *
 * @param httpRequest HTTP request
 * @param includePort when true, include the port
 * @return the host and, optionally, the port specified in the request's Host header
 */
private static String parseHostHeader(HttpRequest httpRequest, boolean includePort) {
    // this header parsing logic is adapted from ClientToProxyConnection#identifyHostAndPort.
    List<String> hosts = httpRequest.headers().getAll(HttpHeaders.Names.HOST);
    if (!hosts.isEmpty()) {
        String hostAndPort = hosts.get(0);

        if (includePort) {
            return hostAndPort;
        } else {
            HostAndPort parsedHostAndPort = HostAndPort.fromString(hostAndPort);
            return parsedHostAndPort.getHost();
        }
    } else {
        return null;
    }
}
 
Example #11
Source File: PublicAccessLogHandlerTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Does a test for the request handling flow with transfer encoding chunked
 */
private void doRequestHandleWithChunkedResponse(boolean useSSL) throws Exception {
  EmbeddedChannel channel = createChannel(useSSL);
  HttpHeaders headers = new DefaultHttpHeaders();
  headers.add(EchoMethodHandler.IS_CHUNKED, "true");
  HttpRequest request = RestTestUtils.createRequest(HttpMethod.POST, "POST", headers);
  HttpUtil.setKeepAlive(request, true);
  sendRequestCheckResponse(channel, request, "POST", headers, false, true, useSSL);
  Assert.assertTrue("Channel should not be closed ", channel.isOpen());
  channel.close();
}
 
Example #12
Source File: HarCaptureFilter.java    From Dream-Catcher with MIT License 5 votes vote down vote up
protected void captureResponseHeaderSize(HttpResponse httpResponse) {
    Log.e("InnerHandle", "captureResponseHeaderSize " + harEntry.getId());
    String statusLine = httpResponse.getProtocolVersion().toString() + ' ' + httpResponse.getStatus().toString();
    // +2 => CRLF after status line, +4 => header/data separation
    long responseHeadersSize = statusLine.length() + 6;
    HttpHeaders headers = httpResponse.headers();
    responseHeadersSize += BrowserMobHttpUtil.getHeaderSize(headers);

    harResponse.getResponse().setHeadersSize(responseHeadersSize);
}
 
Example #13
Source File: LockDeviceRESTHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public FullHttpResponse respond(FullHttpRequest req, ChannelHandlerContext ctx) throws Exception {
   try {
      FullHttpResponse response = super.respond(req, ctx);
      response.headers().set(HttpHeaders.Names.SET_COOKIE, ServerCookieEncoder.STRICT.encode(authenticator.expireCookie()));
      return response;
   } finally {
      try {
         factory.get(ctx.channel()).logout();
      } catch (Throwable t) {
         logger.debug("Error attempting to logout current user", t);
      }
   }
}
 
Example #14
Source File: AdHocSessionAction.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public FullHttpResponse respond(FullHttpRequest req, ChannelHandlerContext ctx) throws Exception {
	doAction(req, ctx);
	DefaultFullHttpResponse res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FOUND);
	res.headers().set(HttpHeaders.Names.LOCATION, redirectUri);
	return res;
}
 
Example #15
Source File: NettyResponseChannelTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Verify satisfaction of all types of requests in both success and non-success cases.
 * @param content the http content used by POST request
 * @param shouldBeSatisfied whether the requests should be satisfied or not
 * @throws IOException
 */
private void verifySatisfactionOfRequests(String content, boolean shouldBeSatisfied) throws IOException {
  byte[] fullRequestBytesArr = TestUtils.getRandomBytes(18);
  RestServiceErrorCode REST_ERROR_CODE = RestServiceErrorCode.AccessDenied;
  HttpRequest httpRequest;
  // headers with error code
  HttpHeaders httpHeaders = new DefaultHttpHeaders();
  httpHeaders.set(MockNettyMessageProcessor.REST_SERVICE_ERROR_CODE_HEADER_NAME, REST_ERROR_CODE);
  httpHeaders.set(MockNettyMessageProcessor.INCLUDE_EXCEPTION_MESSAGE_IN_RESPONSE_HEADER_NAME, "true");
  for (HttpMethod httpMethod : Arrays.asList(HttpMethod.POST, HttpMethod.GET, HttpMethod.PUT, HttpMethod.DELETE,
      HttpMethod.HEAD)) {
    if (httpMethod == HttpMethod.POST || httpMethod == HttpMethod.GET) {
      // success POST/GET requests
      httpRequest = RestTestUtils.createRequest(httpMethod, "/", null);
      sendRequestAndEvaluateResponsePerformance(httpRequest, content, HttpResponseStatus.OK, shouldBeSatisfied);
    } else {
      // success PUT/DELETE/HEAD requests
      httpRequest = RestTestUtils.createFullRequest(httpMethod, TestingUri.ImmediateResponseComplete.toString(), null,
          fullRequestBytesArr);
      sendRequestAndEvaluateResponsePerformance(httpRequest, null, HttpResponseStatus.OK, shouldBeSatisfied);
    }
    // non-success PUT/DELETE/HEAD/POST/GET requests (3xx or 4xx status code)
    httpRequest =
        RestTestUtils.createFullRequest(httpMethod, TestingUri.OnResponseCompleteWithRestException.toString(),
            httpHeaders, fullRequestBytesArr);
    sendRequestAndEvaluateResponsePerformance(httpRequest, null, getExpectedHttpResponseStatus(REST_ERROR_CODE),
        shouldBeSatisfied);
    if (!shouldBeSatisfied) {
      // test 5xx status code
      httpHeaders.set(MockNettyMessageProcessor.REST_SERVICE_ERROR_CODE_HEADER_NAME,
          RestServiceErrorCode.InternalServerError);
      httpRequest =
          RestTestUtils.createFullRequest(httpMethod, TestingUri.OnResponseCompleteWithRestException.toString(),
              httpHeaders, fullRequestBytesArr);
      sendRequestAndEvaluateResponsePerformance(httpRequest, null,
          getExpectedHttpResponseStatus(RestServiceErrorCode.InternalServerError), false);
      httpHeaders.set(MockNettyMessageProcessor.REST_SERVICE_ERROR_CODE_HEADER_NAME, REST_ERROR_CODE);
    }
  }
}
 
Example #16
Source File: MediaTypeCheckerTest.java    From blueflood with Apache License 2.0 5 votes vote down vote up
@Test
public void contentTypeJsonShouldBeValid() {

    HttpHeaders mockHeaders = mock(HttpHeaders.class);
    when(mockHeaders.get(HttpHeaders.Names.CONTENT_TYPE)).thenReturn("application/json");

    assertTrue("content-type application/json should be valid", mediaTypeChecker.isContentTypeValid(mockHeaders));
}
 
Example #17
Source File: WebsocketSinkServerHandler.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
private void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
	// Generate an error page if response getStatus code is not OK (200).
	if (res.getStatus().code() != 200) {
		ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
		res.content().writeBytes(buf);
		buf.release();
		HttpHeaders.setContentLength(res, res.content().readableBytes());
	}

	// Send the response and close the connection if necessary.
	ChannelFuture f = ctx.channel().writeAndFlush(res);
	if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
		f.addListener(ChannelFutureListener.CLOSE);
	}
}
 
Example #18
Source File: NettyToStyxRequestDecoderTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void decodesNettyInternalRequestToStyxRequest() throws Exception {
    FullHttpRequest originalRequest = newHttpRequest("/uri");
    HttpHeaders originalRequestHeaders = originalRequest.headers();
    originalRequestHeaders.add("Foo", "Bar");
    originalRequestHeaders.add("Bar", "Bar");
    originalRequestHeaders.add("Host", "foo.com");

    LiveHttpRequest styxRequest = decode(originalRequest);

    assertThat(styxRequest.id().toString(), is("1"));
    assertThat(styxRequest.url().encodedUri(), is(originalRequest.getUri()));
    assertThat(styxRequest.method(), is(HttpMethod.GET));
    assertThatHttpHeadersAreSame(styxRequest.headers(), originalRequestHeaders);
}
 
Example #19
Source File: HarCaptureFilter.java    From browserup-proxy with Apache License 2.0 5 votes vote down vote up
protected void captureResponseMimeType(HttpResponse httpResponse) {
    String contentType = HttpHeaders.getHeader(httpResponse, HttpHeaderNames.CONTENT_TYPE);
    // don't set the mimeType to null, since mimeType is a required field
    if (contentType != null) {
        harEntry.getResponse().getContent().setMimeType(contentType);
    }
}
 
Example #20
Source File: MediaTypeCheckerTest.java    From blueflood with Apache License 2.0 5 votes vote down vote up
@Test
public void contentTypeEmptyShouldBeValid() {

    HttpHeaders mockHeaders = mock(HttpHeaders.class);
    when(mockHeaders.get(HttpHeaders.Names.CONTENT_TYPE)).thenReturn("");

    assertTrue("empty content-type should be valid", mediaTypeChecker.isContentTypeValid(mockHeaders));
}
 
Example #21
Source File: RiposteWingtipsServerTagAdapterTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    adapterSpy = spy(new RiposteWingtipsServerTagAdapter());
    requestMock = mock(RequestInfo.class);
    responseMock = mock(ResponseInfo.class);
    requestHeadersMock = mock(HttpHeaders.class);

    doReturn(requestHeadersMock).when(requestMock).getHeaders();
}
 
Example #22
Source File: GetHtmlFromCurrentHostPredicateTest.java    From bromium with MIT License 5 votes vote down vote up
@Test
public void whenRequestedTypeIsNotHTMLThenNotChangingURLRequest() throws URISyntaxException {
    URI uri = new URI("http://tenniskafe.com");
    HttpHeaders httpHeaders = mock(HttpHeaders.class);
    when(httpHeaders.get("Accept")).thenReturn("application/json");
    HttpRequest httpRequest = mock(HttpRequest.class);
    when(httpRequest.getUri()).thenReturn("http://google.com");
    when(httpRequest.headers()).thenReturn(httpHeaders);
    when(httpRequest.getMethod()).thenReturn(HttpMethod.GET);

    GetHtmlFromCurrentHostPredicate getHtmlFromCurrentHostPredicate = new GetHtmlFromCurrentHostPredicate(uri);
    assertFalse(getHtmlFromCurrentHostPredicate.test(httpRequest));
}
 
Example #23
Source File: TestAppLaunchHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Test
public void testAndroidUserAgent() throws Exception {
	FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "https://app.arcus.com/app/launch");
	request.headers().add(HttpHeaders.Names.USER_AGENT, "Mozilla/5.0 (Linux; Android 7.0; SAMSUNG SM-G935P Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/5.4 Chrome/51.0.2704.106 Mobile Safari/537.36");
	expectGetClient();
	Capture<SessionHandoff> handoff = captureNewToken();
	replay();
	
	FullHttpResponse response = handler.respond(request, mockContext());
	assertHandoff(handoff.getValue());
	assertRedirectTo(response, "https://dev-app.arcus.com/android/run?token=token");
}
 
Example #24
Source File: ClientToProxyConnection.java    From g4proxy with Apache License 2.0 5 votes vote down vote up
/**
 * Determine whether or not the client connection should be closed.
 * 
 * @param req
 * @param res
 * @param httpObject
 * @return
 */
private boolean shouldCloseClientConnection(HttpRequest req,
        HttpResponse res, HttpObject httpObject) {
    if (ProxyUtils.isChunked(res)) {
        // If the response is chunked, we want to return false unless it's
        // the last chunk. If it is the last chunk, then we want to pass
        // through to the same close semantics we'd otherwise use.
        if (httpObject != null) {
            if (!ProxyUtils.isLastChunk(httpObject)) {
                String uri = null;
                if (req != null) {
                    uri = req.getUri();
                }
                LOG.debug("Not closing client connection on middle chunk for {}", uri);
                return false;
            } else {
                LOG.debug("Handling last chunk. Using normal client connection closing rules.");
            }
        }
    }

    if (!HttpHeaders.isKeepAlive(req)) {
        LOG.debug("Closing client connection since request is not keep alive: {}", req);
        // Here we simply want to close the connection because the
        // client itself has requested it be closed in the request.
        return true;
    }

    // ignore the response's keep-alive; we can keep this client connection open as long as the client allows it.

    LOG.debug("Not closing client connection for request: {}", req);
    return false;
}
 
Example #25
Source File: HttpObjectUtil.java    From CapturePacket with MIT License 5 votes vote down vote up
/**
 * Replaces an HTTP entity body with the specified binary contents.
 * TODO: Currently this method only works for FullHttpMessages, since it must modify the Content-Length header; determine if this may be applied to chunked messages as well
 *
 * @param message the HTTP message to manipulate
 * @param newBinaryContents the new entity body contents
 */
public static void replaceBinaryHttpEntityBody(FullHttpMessage message, byte[] newBinaryContents) {
    message.content().resetWriterIndex();
    // resize the buffer if needed, since the new message may be longer than the old one
    message.content().ensureWritable(newBinaryContents.length, true);
    message.content().writeBytes(newBinaryContents);

    // update the Content-Length header, since the size may have changed
    message.headers().set(HttpHeaders.Names.CONTENT_LENGTH, newBinaryContents.length);
}
 
Example #26
Source File: BrowserUpHttpUtil.java    From browserup-proxy with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the size of the headers, including the 2 CRLFs at the end of the header block.
 *
 * @param headers headers to size
 * @return length of the headers, in bytes
 */
public static long getHeaderSize(HttpHeaders headers) {
    // +2 for ': ', +2 for new line
    return headers.entries().stream()
            .mapToLong(header -> header.getKey().length() + header.getValue().length() + 4)
            .sum();
}
 
Example #27
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 #28
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 #29
Source File: HttpProcessHandler.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
private static final FullHttpResponse http_200(String result) {
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
            Unpooled.wrappedBuffer(result.getBytes()));
    HttpHeaders httpHeaders = response.headers();
    httpHeaders.set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
    httpHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
    return response;
}
 
Example #30
Source File: HttpClient.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
/**
 * Apply headers configuration emitted by the returned Mono before requesting.
 *
 * @param headerBuilder the header {@link Function} to invoke before sending
 *
 * @return a new {@link HttpClient}
 */
public final HttpClient headersWhen(Function<? super HttpHeaders, Mono<? extends HttpHeaders>> headerBuilder) {
	Objects.requireNonNull(headerBuilder, "headerBuilder");
	HttpClient dup = duplicate();
	dup.configuration().deferredConf(config ->
			headerBuilder.apply(config.headers.copy())
			             .map(h -> {
			                 config.headers = h;
			                 return config;
			             }));
	return dup;
}