Request buildRequest() { RequestBuilder builder = new RequestBuilder(method); builder.setUrl(url); builder.setQueryParams(new FluentStringsMap(queryParameters)); builder.setHeaders(headers); if (body == null) { // do nothing } else if (body instanceof String) { String stringBody = ((String) body); FluentCaseInsensitiveStringsMap headers = new FluentCaseInsensitiveStringsMap(this.headers); // Detect and maybe add charset String contentType = headers.getFirstValue(HttpHeaders.Names.CONTENT_TYPE); if (contentType == null) { contentType = "text/plain"; } Charset charset = HttpUtils.parseCharset(contentType); if (charset == null) { charset = StandardCharsets.UTF_8; List<String> contentTypeList = new ArrayList<String>(); contentTypeList.add(contentType + "; charset=utf-8"); headers.replace(HttpHeaders.Names.CONTENT_TYPE, contentTypeList); } byte[] bodyBytes; bodyBytes = stringBody.getBytes(charset); // If using a POST with OAuth signing, the builder looks at // getFormParams() rather than getBody() and constructs the signature // based on the form params. if (contentType.equals(HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED)) { Map<String, List<String>> stringListMap = FormUrlEncodedParser.parseAsJava(stringBody, "utf-8"); for (String key : stringListMap.keySet()) { List<String> values = stringListMap.get(key); for (String value : values) { builder.addFormParam(key, value); } } } else { builder.setBody(stringBody); } builder.setHeaders(headers); builder.setBodyCharset(charset); } else if (body instanceof JsonNode) { JsonNode jsonBody = (JsonNode) body; FluentCaseInsensitiveStringsMap headers = new FluentCaseInsensitiveStringsMap(this.headers); List<String> contentType = new ArrayList<String>(); contentType.add("application/json; charset=utf-8"); headers.replace(HttpHeaders.Names.CONTENT_TYPE, contentType); String bodyStr = Json.stringify(jsonBody); byte[] bodyBytes; try { bodyBytes = bodyStr.getBytes("utf-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } builder.setBody(bodyStr); builder.setHeaders(headers); builder.setBodyCharset(StandardCharsets.UTF_8); } else if (body instanceof File) { File fileBody = (File) body; FileBodyGenerator bodyGenerator = new FileBodyGenerator(fileBody); builder.setBody(bodyGenerator); } else if (body instanceof InputStream) { InputStream inputStreamBody = (InputStream) body; InputStreamBodyGenerator bodyGenerator = new InputStreamBodyGenerator(inputStreamBody); builder.setBody(bodyGenerator); } else if (body instanceof Source) { Source<ByteString, ?> sourceBody = (Source<ByteString, ?>) body; Publisher<ByteBuffer> publisher = sourceBody.map(ByteString::toByteBuffer).runWith(Sink.asPublisher(false), materializer); builder.setBody(publisher); } else { throw new IllegalStateException("Impossible body: " + body); } if (this.timeout == -1 || this.timeout > 0) { builder.setRequestTimeout(this.timeout); } if (this.followRedirects != null) { builder.setFollowRedirect(this.followRedirects); } if (this.virtualHost != null) { builder.setVirtualHost(this.virtualHost); } if (this.username != null && this.password != null && this.scheme != null) { builder.setRealm(auth(this.username, this.password, this.scheme)); } if (this.calculator != null) { if (this.calculator instanceof OAuth.OAuthCalculator) { OAuthSignatureCalculator calc = ((OAuth.OAuthCalculator) this.calculator).getCalculator(); builder.setSignatureCalculator(calc); } else { throw new IllegalStateException("Use OAuth.OAuthCalculator"); } } return builder.build(); }
public NettyRequest newNettyRequest( Request request, boolean forceConnect, ProxyServer proxyServer) throws IOException { Uri uri = request.getUri(); HttpMethod method = forceConnect ? HttpMethod.CONNECT : HttpMethod.valueOf(request.getMethod()); boolean connect = method == HttpMethod.CONNECT; boolean allowConnectionPooling = config.isAllowPoolingConnections() && (!HttpUtils.isSecure(uri) || config.isAllowPoolingSslConnections()); HttpVersion httpVersion = !allowConnectionPooling || (connect && proxyServer.isForceHttp10()) ? HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1; String requestUri = requestUri(uri, proxyServer, connect); NettyBody body = body(request, connect); HttpRequest httpRequest; NettyRequest nettyRequest; if (body instanceof NettyDirectBody) { ChannelBuffer buffer = NettyDirectBody.class.cast(body).channelBuffer(); httpRequest = new DefaultHttpRequest(httpVersion, method, requestUri); // body is passed as null as it's written directly with the request httpRequest.setContent(buffer); nettyRequest = new NettyRequest(httpRequest, null); } else { httpRequest = new DefaultHttpRequest(httpVersion, method, requestUri); nettyRequest = new NettyRequest(httpRequest, body); } HttpHeaders headers = httpRequest.headers(); if (!connect) { // assign headers as configured on request for (Entry<String, List<String>> header : request.getHeaders()) { headers.set(header.getKey(), header.getValue()); } if (isNonEmpty(request.getCookies())) headers.set(COOKIE, CookieEncoder.encode(request.getCookies())); if (config.isCompressionEnforced() && !headers.contains(ACCEPT_ENCODING)) headers.set(ACCEPT_ENCODING, GZIP_DEFLATE); } if (body != null) { if (body.getContentLength() < 0) headers.set(TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED); else headers.set(CONTENT_LENGTH, body.getContentLength()); if (body.getContentType() != null) headers.set(CONTENT_TYPE, body.getContentType()); } // connection header and friends boolean webSocket = isWebSocket(uri.getScheme()); if (!connect && webSocket) { String origin = "http://" + uri.getHost() + ":" + (uri.getPort() == -1 ? isSecure(uri.getScheme()) ? 443 : 80 : uri.getPort()); headers .set(UPGRADE, HttpHeaders.Values.WEBSOCKET) // .set(CONNECTION, HttpHeaders.Values.UPGRADE) // .set(ORIGIN, origin) // .set(SEC_WEBSOCKET_KEY, getKey()) // .set(SEC_WEBSOCKET_VERSION, "13"); } else if (!headers.contains(CONNECTION)) { String connectionHeaderValue = connectionHeader(allowConnectionPooling, httpVersion == HttpVersion.HTTP_1_1); if (connectionHeaderValue != null) headers.set(CONNECTION, connectionHeaderValue); } if (!headers.contains(HOST)) headers.set(HOST, hostHeader(request, uri)); Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm(); // don't override authorization but append addAuthorizationHeader(headers, systematicAuthorizationHeader(request, realm)); setProxyAuthorizationHeader( headers, systematicProxyAuthorizationHeader(request, proxyServer, realm, connect)); // Add default accept headers if (!headers.contains(ACCEPT)) headers.set(ACCEPT, "*/*"); // Add default user agent if (!headers.contains(USER_AGENT) && config.getUserAgent() != null) headers.set(USER_AGENT, config.getUserAgent()); return nettyRequest; }