/**
  * Sets a header with the given name, this can be called repeatedly.
  *
  * @param name the header name
  * @param value the header value
  * @return the receiving WSRequest, with the new header set.
  */
 @Override
 public AhcWSRequest setHeader(String name, String value) {
   if (headers.containsKey(name)) {
     Collection<String> values = headers.get(name);
     values.add(value);
   } else {
     List<String> values = new ArrayList<String>();
     values.add(value);
     headers.put(name, values);
   }
   return this;
 }
 @Override
 public WSRequest setQueryParameter(String name, String value) {
   if (queryParameters.containsKey(name)) {
     Collection<String> values = queryParameters.get(name);
     values.add(value);
   } else {
     List<String> values = new ArrayList<String>();
     values.add(value);
     queryParameters.put(name, values);
   }
   return this;
 }
  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();
  }