Class api sets up the request to the SendGrid API, this is main interface.
@param request the request object.
@return the response object.
@throws IOException in case of a network error.
359833
public Response api(Request request) throws IOException {
    Request req = new Request();
    req.setMethod(request.getMethod());
    req.setBaseUri(this.host);
    req.setEndpoint("/" + version + "/" + request.getEndpoint());
    req.setBody(request.getBody());
    for (Map.Entry<String, String> header : this.requestHeaders.entrySet()) {
      req.addHeader(header.getKey(), header.getValue());
    }
    for (Map.Entry<String, String> queryParam : request.getQueryParams().entrySet()) {
      req.addQueryParam(queryParam.getKey(), queryParam.getValue());
    }

    return makeCall(req);
  }
1146413
public CreateSessionResponse createSession(CreateSessionRequest request) {
        checkNotNull(request, "The parameter request should NOT be null.");

        if (request.getPreset() == null && request.getPresets() == null) {
            throw new IllegalArgumentException("The parameter preset and presets should NOT both be null or empty.");
        }

        InternalRequest internalRequest = createRequest(HttpMethodName.POST, request, LIVE_SESSION);
        return invokeHttpClient(internalRequest, CreateSessionResponse.class);
    }
241793
private String getRequestContent(HttpServletRequest request) throws IOException {
        StringBuilder builder = new StringBuilder();
        
        builder.append(request.getProtocol());
        builder.append(" ");
        builder.append(request.getMethod());
        builder.append(" ");
        builder.append(request.getRequestURI());
        builder.append(NEWLINE);
        
        Enumeration<?> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement().toString();
            
            builder.append(headerName);
            builder.append(":");
            
            Enumeration<?> headerValues = request.getHeaders(headerName);
            if (headerValues.hasMoreElements()) {
                builder.append(headerValues.nextElement());
            }
            
            while (headerValues.hasMoreElements()) {
                builder.append(",");
                builder.append(headerValues.nextElement());
            }
            
            builder.append(NEWLINE);
        }
        
        builder.append(NEWLINE);
        builder.append(FileUtils.readToString(request.getInputStream()));
        
        return builder.toString();
    }
284878
protected Response executeRequest(Request request)
    {
        try
        {
            com.squareup.okhttp.Request httpRequest = buildHttpRequest(request);

            if(logger.isInfoEnabled())
                logger.info("Sending request: {} {}",httpRequest.method(),httpRequest.urlString());

            if(logger.isDebugEnabled() && request.getRequestMethod().isBodyRequest())
            {
                Buffer buffer = new Buffer();
                httpRequest.body().writeTo(buffer);
                if(maxLoggedBodySize == -1 || buffer.size() <= maxLoggedBodySize )
                    logger.debug("Request body: {}", buffer.readUtf8());
                else
                    logger.debug("Request body not captured: too large. ");
            }

            if(logger.isTraceEnabled())
                logger.trace("Request headers: {}",httpRequest.headers().toString());

            Response response = client.newCall(httpRequest).execute();

            if(response.code() == HttpURLConnection.HTTP_UNAUTHORIZED && authorizationFactory != null
                    && authorizationFactory.retryOnAuthenticationError())
            {
                if(authorizationFactory instanceof ResettableAuthorizationFactory)
                    ((ResettableAuthorizationFactory) authorizationFactory).reset();

                response = client.newCall(httpRequest).execute();
            }

            logger.info("Response code: {}",response.code());

            if(logger.isTraceEnabled())
                logger.trace("Response headers: {}",response.headers().toString());

            if(logger.isDebugEnabled())
            {
                ByteArrayOutputStream copy = new ByteArrayOutputStream();
                copy(response.body().byteStream(),copy);
                response = response.newBuilder().body(ResponseBody.create(response.body().contentType(),copy.toByteArray())).build();

                if(maxLoggedBodySize == -1 || copy.size() <= maxLoggedBodySize)
                    logger.debug("Response body: {}",copy.toString());
                else
                    logger.debug("Response body not captured: too large.");
            }
            if (response.code() >= HttpURLConnection.HTTP_BAD_REQUEST)
            {
                throw readException(response);
            }

            return response;
        }
        catch (IOException e)
        {
            throw new ClientConnectionException("Error calling service.",e);
        }

    }
1107695
public Nfs3CreateResponse sendCreate(NfsCreateRequest request) throws IOException {
        Nfs3CreateResponse response = new Nfs3CreateResponse();
        _rpcWrapper.callRpcNaked(request, response);
        return response;
    }
535434
public static WrappedRequest wrap(final HttpServletRequest request) throws IOException {
        if (request instanceof WrappedRequest) {
            return (WrappedRequest) request;
        }

        return new WrappedRequest(request);
    }
771090
protected void sendRequest(HttpURLConnection connection, Request request) throws IOException {
        // Set up the request.
        connection.setRequestMethod(request.method);
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Authorization", request.authorization);

        // If a different HttpHandler is used, we won't get this header. We would need to refactor
        // to a delegation pattern to give the client code's HttpHandler a chance to process the
        // Request first, then attach our custom headers, which would likely be a breaking change.
        connection.setRequestProperty("Keen-Sdk", "java-" + KeenVersion.getSdkVersion());

        // If the request has a body, send it. Otherwise just connect.
        if (request.body != null) {
            if (HttpMethods.GET.equals(request.method) ||
                HttpMethods.DELETE.equals(request.method)) {
                throw new IllegalStateException("Trying to send a GET request with a request " +
                                                "body, which would result in sending a POST.");
            }

            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            request.body.writeTo(connection.getOutputStream());
        } else {
            connection.connect();
        }
    }
197324
public Nfs3CreateResponse wrapped_sendCreate(NfsCreateRequest request) throws IOException {
        NfsResponseHandler<Nfs3CreateResponse> responseHandler = new NfsResponseHandler<Nfs3CreateResponse>() {

            /* (non-Javadoc)
             * @see com.emc.ecs.nfsclient.rpc.RpcResponseHandler#makeNewResponse()
             */
            protected Nfs3CreateResponse makeNewResponse() {
                return new Nfs3CreateResponse();
            }

        };
        _rpcWrapper.callRpcWrapped(request, responseHandler);
        return responseHandler.getResponse();
    }
446919
public Map<String, Object> send(GetItemValues request) throws ApiException {
        String responseStr = sendRequest(request);

        TypeReference<HashMap<String,Object>> typeRef 
                = new TypeReference<HashMap<String,Object>>() {};
        try {
            return this.mapper.readValue(responseStr, typeRef);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
768532
public Task<HttpResponse> execute(@NonNull final HttpRequest request) {
    return dispatcher.dispatchTask(new Callable<HttpResponse>() {
      @Override
      public HttpResponse call() {
        return proxy.execute(request);
      }
    });
  }
1346119
public HttpResponse sendRequest(PiwikRequest request) throws IOException{
        HttpClient client = getHttpClient();
        uriBuilder.replaceQuery(request.getUrlEncodedQueryString());
        HttpGet get = new HttpGet(uriBuilder.build());

        try {
            return client.execute(get);
        } finally {
            get.releaseConnection();
        }
    }
1075090
protected HttpResponse sendImpl() throws IOException {
    HttpURLConnection con = (HttpURLConnection) uri.toURL().openConnection();
    con.setConnectTimeout(connectTimeout);
    con.setReadTimeout(readTimeout);
    con.setRequestMethod(method);
    for (Map.Entry<String, String> h : reqHeaders.entrySet()) {
      con.setRequestProperty(h.getKey(), h.getValue());
    }
    configureHTTPS(con);

    boolean canRetry = true;
    try {
      con.setDoInput(true);

      // HttpURLConnection will change method to POST if there is a body associated
      // with a GET request. Only try to write entity if it is not empty.
      entry.withRequestContentLength(entity.length).mark("start");
      if (entity.length > 0) {
        con.setDoOutput(true);
        try (OutputStream out = con.getOutputStream()) {
          out.write(entity);
        }
      }

      int status = con.getResponseCode();
      canRetry = (status >= 500 || status == 429);
      entry.mark("complete").withStatusCode(status);

      // A null key is used to return the status line, remove it before sending to
      // the log entry or creating the response object
      Map<String, List<String>> headers = new LinkedHashMap<>(con.getHeaderFields());
      headers.remove(null);
      for (Map.Entry<String, List<String>> h : headers.entrySet()) {
        for (String v : h.getValue()) {
          entry.withResponseHeader(h.getKey(), v);
        }
      }

      try (InputStream in = (status >= 400) ? con.getErrorStream() : con.getInputStream()) {
        byte[] data = readAll(in);
        entry.withResponseContentLength(data.length);
        return new HttpResponse(status, headers, data);
      }
    } catch (IOException e) {
      entry.mark("complete").withException(e);
      throw e;
    } finally {
      entry.withCanRetry(canRetry);
      HttpLogEntry.logClientRequest(entry);
    }
  }
79275
public Request protectRequest(Request request) throws IOException {
        try {
            Request result = request.newBuilder().header(AUTHENTICATE, BEARER_TOKEP_REFIX + clientSecurityToken)
                    .build();

            if (!supportsProtection()) {
                return result;
            }

            Buffer buffer = new Buffer();
            request.body().writeTo(buffer);
            String currentbody = buffer.readUtf8();

            if (currentbody == null || currentbody.length() == 0) {
                return result;
            }

            JsonWebKey clientPublicEncryptionKey = MessageSecurityHelper.getJwkWithPublicKeyOnly(clientEncryptionKey);

            String payload = currentbody.substring(0, currentbody.length() - 1) + ",\"rek\":{\"jwk\":"
                    + clientPublicEncryptionKey.toString() + "}}";

            JWEObject jweObject = protectPayload(payload);

            JWSHeader jwsHeader = new JWSHeader("RS256", clientSignatureKey.kid(), clientSecurityToken,
                    getCurrentTimestamp(), "PoP", null);

            String jwsHeaderJsonb64 = MessageSecurityHelper.stringToBase64Url(jwsHeader.serialize());
            String protectedPayload = MessageSecurityHelper.stringToBase64Url(jweObject.serialize());
            byte[] data = (jwsHeaderJsonb64 + "." + protectedPayload).getBytes(MESSAGE_ENCODING);

            RsaKey clientSignatureRsaKey = new RsaKey(clientSignatureKey.kid(), clientSignatureKey.toRSA(true));
            Pair<byte[], String> signature = clientSignatureRsaKey.signAsync(getSha256(data), "RS256").get();

            JWSObject jwsObject = new JWSObject(jwsHeader, protectedPayload,
                    MessageSecurityHelper.bytesToBase64Url(signature.getKey()));

            RequestBody body = RequestBody.create(MediaType.parse("application/jose+json"), jwsObject.serialize());

            return result.newBuilder().method(request.method(), body).build();
        } catch (ExecutionException e) {
            // unexpected;
            return null;
        } catch (InterruptedException e) {
            // unexpected;
            return null;
        } catch (NoSuchAlgorithmException e) {
            // unexpected;
            return null;
        }
    }
663403
public SetDomainCacheTTLResponse setDomainCacheTTL(SetDomainCacheTTLRequest request) {
        checkNotNull(request, "The parameter request should NOT be null.");
        InternalRequest internalRequest = createRequest(request, HttpMethodName.PUT, DOMAIN, request.getDomain(), "config");
        internalRequest.addParameter("cacheTTL","");
        this.attachRequestToBody(request, internalRequest);
        return invokeHttpClient(internalRequest, SetDomainCacheTTLResponse.class);
    }
412870
public <T> T send(Request<T> request) {

		if (request == null) {
			throw new CommunicationErrorException("Request cannot be null.");
		}
		RequestUtil.validate(request);

		@SuppressWarnings("unchecked")
		T response = (T) dispatchByMethod(request);

		return response;
	}
490271
public void checkResponse(RpcRequest request) throws IOException {
        if (getResponse().getRejectStatus() == RejectStatus.AUTH_ERROR.getValue()) {
            request.setUsePrivilegedPort(true);
        }
        if (getResponse().getState() != NfsStatus.NFS3_OK.getValue()) {
            int responseState = getResponse().getState();
            if (responseState == NfsStatus.NFS3ERR_NOENT.getValue()) {
                throw new FileNotFoundException(request.getErrorMessage());
            }
            NfsStatus status = NfsStatus.fromValue(responseState);
            throw new NfsException(status, request.getErrorMessage() + " error code:" + status.toString());
        }
    }
406980
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
    private com.jcabi.http.Request request(final Request req,
        final URI dest) throws IOException {
        final String method = new RqMethod.Base(req).method();
        com.jcabi.http.Request proxied = new JdkRequest(dest).method(method);
        final RqHeaders headers = new RqHeaders.Base(req);
        for (final String name : headers.names()) {
            if ("content-length".equals(new EnglishLowerCase(name).string())) {
                continue;
            }
            if (TkProxy.isHost(name)) {
                proxied = proxied.header(name, this.target);
                continue;
            }
            for (final String value : headers.header(name)) {
                proxied = proxied.header(name, value);
            }
        }
        if (headers.header("Content-Length").iterator().hasNext()
            || headers.header("Transfer-Encoding").iterator().hasNext()) {
            final ByteArrayOutputStream output = new ByteArrayOutputStream();
            new RqPrint(new RqLengthAware(req)).printBody(output);
            proxied = proxied.body().set(output.toByteArray()).back();
        }
        return proxied;
    }