Performs the given request, returning an HttpResponse object that wraps
the actual web server response.

@param request
a request object.
@return
a response object.
@throws IOException
@throws HttpClientException
163277
public HttpResponse perform(HttpRequest request) throws IOException, HttpClientException {
		
		// first check if the request is a multipart/form-data and the method is
		// not POST: if so, there's something inconsistent and we just bail out
		if(request.isMultiPartFormData() && request.getMethod() != HttpMethod.POST) {
			logger.error("multipart/form-data can only be conveyed through a POST, using {} instead", request.getMethod().name());
			throw new HttpClientException("multipart/form-data cannot be conveyed through a " + request.getMethod().name() + " request");
		}
		
		URL url = request.getURL();		
		HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy != null ? proxy : Proxy.NO_PROXY);
		// optional default is GET
		connection.setRequestMethod(request.getMethod().name());
		for(Entry<String, String> header : request.getHeaders().entrySet()) {
			connection.setRequestProperty(header.getKey(), header.getValue());
		}
		
		if(request.getMethod() == HttpMethod.POST) {
			// add headers directly to the connection (we've already looped over
			// headers in the request object, so it's too late to add headers now)
			if(request.isMultiPartFormData()) {
				connection.setRequestProperty("Content-type", "multipart/form-data, boundary=" + request.getBoundary());
			} else {
				connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
			}
						
			connection.setDoOutput(true);
//			try(MirrorOutputStream mirror = new MirrorOutputStream(connection.getOutputStream(), new FileOutputStream("target/request.dat")); DataOutputStream stream = new DataOutputStream(mirror)) {
			try(DataOutputStream stream = new DataOutputStream(connection.getOutputStream())) {
				if(request.isMultiPartFormData()) {
					//
					// multipart/form-encoded format is:
					//
					// ========================
					// POST /path/to/script.php HTTP/1.0
					// Host: example.com
					// Content-type: multipart/form-data, boundary=<RANDOM BOUNDARY>
					// Content-Length: <REQUEST_LENGTH>
					//
					// --<RANDOM BOUNDARY>
					// Content-Disposition: form-data; name="field1"
					//
					// value1
					// --<RANDOM BOUNDARY>
					// Content-Disposition: form-data; name="field2"
					//
					// value2
					// --<RANDOM BOUNDARY>
					// Content-Disposition: form-data; name="file1"; filename="<NAME OF FILE 1>"
					// Content-Type: <FILE 1 MIME TYPE>
					// Content-Transfer-Encoding: binary
					// 
					// <FILE 1 BINARY DATA>
					// --<RANDOM BOUNDARY>
					// Content-Disposition: form-data; name="file2"; filename="<NAME OF FILE 2>"
					// Content-Type: <FILE 2 MIME TYPE>
					// Content-Transfer-Encoding: binary
					// 
					// <FILE 2 BINARY DATA>
					// --<RANDOM BOUNDARY>--
					// ==========================						
					for(HttpParameter parameter : request.getParameters()) {
						stream.writeBytes("--" + request.getBoundary());
						stream.writeBytes(NEWLINE);
						switch(parameter.getType()) {
						case TEXT:
							stream.writeBytes("Content-Disposition: form-data; name=\"" + parameter.getName() + "\"" + NEWLINE);
							stream.writeBytes(NEWLINE);
							stream.writeBytes(((HttpTextParameter)parameter).getValue().toString() + NEWLINE);
							break;
						case FILE:
							stream.writeBytes("Content-Disposition: form-data; name=\"" + parameter.getName() + "\"; filename=\"" + ((HttpFileParameter)parameter).getFileName() + "\"" + NEWLINE);
							stream.writeBytes("Content-Type: " + ((HttpFileParameter)parameter).getContentType() + NEWLINE);
							stream.writeBytes("Content-Transfer-Encoding: binary" + NEWLINE);
							stream.writeBytes(NEWLINE);
							Streams.copy(((HttpFileParameter)parameter).getInputStream(), stream);
							stream.writeBytes(NEWLINE);
							break;						
						}
					}					
					stream.writeBytes("--" + request.getBoundary() + "--");
				} else {
					//
					// plain old form format is:
					//
					// ========================
					// POST /path/to/script.php HTTP/1.0
					// Host: example.com
					// Content-type: application/x-www-form-urlencoded
					// Content-Length: <CONTENT LENGTH>
					//
					// logfile=blabla&configfile=more+blabla&usercomment=hello&useremail=
					// ==========================						
					//
					String values = HttpParameter.concatenate(request.getParameters());
					stream.writeBytes(values);
				}
			
				stream.flush();
				stream.close();
			}
		} else if(request.getMethod() == HttpMethod.GET) {
			// do nothing
		}
		
		return new HttpResponse(connection);
	}
914382
public void initialize(AbstractGoogleClientRequest<?> request) throws IOException {
    if (key != null) {
      request.put("key", key);
    }
    if (userIp != null) {
      request.put("userIp", userIp);
    }
  }
264526
public CommandResponse execute(GwtCommand request) {
		if (request != null) {
			return commandDispatcher.execute(request.getCommandName(), request.getCommandRequest(),
					request.getUserToken(), request.getLocale());
		}
		return null;
	}
331189
private HttpResponse execute( HttpUriRequest request ) throws RestException
    {
        log.debug( ">>>> " + request.getRequestLine() );
        for ( Header header : request.getAllHeaders() )
        {
            log.trace( ">>>> " + header.getName() + ": " + header.getValue() );
        }

        HttpResponse response;
        try
        {
            response = getHttpClient().execute( request );
            log.debug( "<<<< " + response.getStatusLine() );
            for ( Header header : response.getAllHeaders() )
            {
                log.trace( "<<<< " + header.getName() + ": " + header.getValue() );
            }

            if ( response.getStatusLine().getStatusCode() == 204 )
            {
                log.debug( "Consuming quietly the response entity since server returned no content" );
                EntityUtils.consumeQuietly( response.getEntity() );
            }

            checkError( response );
            return response;
        }
        catch ( KeyManagementException | NoSuchAlgorithmException | IOException e )
        {
            throw new RuntimeRestException( e );
        }
        finally
        {
            // https://issues.apache.org/jira/browse/HTTPCLIENT-1523
            DateUtils.clearThreadLocal();
        }
    }
870740
public HttpResponse request(HttpRequest smartsheetRequest) throws HttpClientException {
        Util.throwIfNull(smartsheetRequest);
        if (smartsheetRequest.getUri() == null) {
            throw new IllegalArgumentException("A Request URI is required.");
        }

        int attempt = 0;
        long start = System.currentTimeMillis();

        HttpRequestBase apacheHttpRequest;
        HttpResponse smartsheetResponse;

        InputStream bodyStream = null;
        if(smartsheetRequest.getEntity() != null && smartsheetRequest.getEntity().getContent() != null) {
            bodyStream = smartsheetRequest.getEntity().getContent();
        }
        // the retry logic will consume the body stream so we make sure it supports mark/reset and mark it
        boolean canRetryRequest = bodyStream == null || bodyStream.markSupported();
        if (!canRetryRequest) {
            try {
                // attempt to wrap the body stream in a input-stream that does support mark/reset
                bodyStream = new ByteArrayInputStream(StreamUtil.readBytesFromStream(bodyStream));
                // close the old stream (just to be tidy) and then replace it with a reset-able stream
                smartsheetRequest.getEntity().getContent().close();
                smartsheetRequest.getEntity().setContent(bodyStream);
                canRetryRequest = true;
            }
            catch(IOException ignore) {
            }
        }

        // the retry loop
        while(true) {

            apacheHttpRequest = createApacheRequest(smartsheetRequest);

            // Set HTTP headers
            if (smartsheetRequest.getHeaders() != null) {
                for (Map.Entry<String, String> header : smartsheetRequest.getHeaders().entrySet()) {
                    apacheHttpRequest.addHeader(header.getKey(), header.getValue());
                }
            }

            HttpEntitySnapshot requestEntityCopy = null;
            HttpEntitySnapshot responseEntityCopy = null;
            // Set HTTP entity
            final HttpEntity entity = smartsheetRequest.getEntity();
            if (apacheHttpRequest instanceof HttpEntityEnclosingRequestBase && entity != null && entity.getContent() != null) {
                try {
                    // we need access to the original request stream so we can log it (in the event of errors and/or tracing)
                    requestEntityCopy = new HttpEntitySnapshot(entity);
                } catch (IOException iox) {
                    logger.error("failed to make copy of original request entity - {}", iox);
                }

                InputStreamEntity streamEntity = new InputStreamEntity(entity.getContent(), entity.getContentLength());
                streamEntity.setChunked(false);    // why?  not supported by library?
                ((HttpEntityEnclosingRequestBase) apacheHttpRequest).setEntity(streamEntity);
            }

            // mark the body so we can reset on retry
            if(canRetryRequest && bodyStream != null) {
                bodyStream.mark((int)smartsheetRequest.getEntity().getContentLength());
            }

            // Make the HTTP request
            smartsheetResponse = new HttpResponse();
            HttpContext context = new BasicHttpContext();
            try {
                long startTime = System.currentTimeMillis();
                apacheHttpResponse = this.httpClient.execute(apacheHttpRequest, context);
                long endTime = System.currentTimeMillis();

                // Set request headers to values ACTUALLY SENT (not just created by us), this would include:
                // 'Connection', 'Accept-Encoding', etc. However, if a proxy is used, this may be the proxy's CONNECT
                // request, hence the test for HTTP method first
                Object httpRequest = context.getAttribute("http.request");
                if(httpRequest != null && HttpRequestWrapper.class.isAssignableFrom(httpRequest.getClass())) {
                    HttpRequestWrapper actualRequest = (HttpRequestWrapper)httpRequest;
                    switch(HttpMethod.valueOf(actualRequest.getMethod())) {
                        case GET:
                        case POST:
                        case PUT:
                        case DELETE:
                            apacheHttpRequest.setHeaders(((HttpRequestWrapper)httpRequest).getAllHeaders());
                            break;
                    }
                }

                // Set returned headers
                smartsheetResponse.setHeaders(new HashMap<String, String>());
                for (Header header : apacheHttpResponse.getAllHeaders()) {
                    smartsheetResponse.getHeaders().put(header.getName(), header.getValue());
                }
                smartsheetResponse.setStatus(apacheHttpResponse.getStatusLine().getStatusCode(),
                        apacheHttpResponse.getStatusLine().toString());

                // Set returned entities
                if (apacheHttpResponse.getEntity() != null) {
                    HttpEntity httpEntity = new HttpEntity();
                    httpEntity.setContentType(apacheHttpResponse.getEntity().getContentType().getValue());
                    httpEntity.setContentLength(apacheHttpResponse.getEntity().getContentLength());
                    httpEntity.setContent(apacheHttpResponse.getEntity().getContent());
                    smartsheetResponse.setEntity(httpEntity);
                    responseEntityCopy = new HttpEntitySnapshot(httpEntity);
                }

                long responseTime = endTime - startTime;
                logRequest(apacheHttpRequest, requestEntityCopy, smartsheetResponse, responseEntityCopy, responseTime);

                if (traces.size() > 0) { // trace-logging of request and response (if so configured)
                    RequestAndResponseData requestAndResponseData = RequestAndResponseData.of(apacheHttpRequest,
                            requestEntityCopy, smartsheetResponse, responseEntityCopy, traces);
                    TRACE_WRITER.println(requestAndResponseData.toString(tracePrettyPrint));
                }

                if (smartsheetResponse.getStatusCode() == 200) {
                    // call successful, exit the retry loop
                    break;
                }

                // the retry logic might consume the content stream so we make sure it supports mark/reset and mark it
                InputStream contentStream = smartsheetResponse.getEntity().getContent();
                if (!contentStream.markSupported()) {
                    // wrap the response stream in a input-stream that does support mark/reset
                    contentStream = new ByteArrayInputStream(StreamUtil.readBytesFromStream(contentStream));
                    // close the old stream (just to be tidy) and then replace it with a reset-able stream
                    smartsheetResponse.getEntity().getContent().close();
                    smartsheetResponse.getEntity().setContent(contentStream);
                }
                try {
                    contentStream.mark((int) smartsheetResponse.getEntity().getContentLength());
                    long timeSpent = System.currentTimeMillis() - start;
                    if (!shouldRetry(++attempt, timeSpent, smartsheetResponse)) {
                        // should not retry, or retry time exceeded, exit the retry loop
                        break;
                    }
                } finally {
                    if(bodyStream != null) {
                        bodyStream.reset();
                    }
                    contentStream.reset();
                }
                // moving this to finally causes issues because socket is closed (which means response stream is closed)
                this.releaseConnection();

            } catch (ClientProtocolException e) {
                try {
                    logger.warn("ClientProtocolException " + e.getMessage());
                    logger.warn("{}", RequestAndResponseData.of(apacheHttpRequest, requestEntityCopy, smartsheetResponse,
                            responseEntityCopy, REQUEST_RESPONSE_SUMMARY));
                    // if this is a PUT and was retried by the http client, the body content stream is at the
                    // end and is a NonRepeatableRequest. If we marked the body content stream prior to execute,
                    // reset and retry
                    if (canRetryRequest && e.getCause() instanceof NonRepeatableRequestException) {
                        if (smartsheetRequest.getEntity() != null) {
                            smartsheetRequest.getEntity().getContent().reset();
                        }
                        continue;
                    }
                } catch (IOException ignore) {
                }
                throw new HttpClientException("Error occurred.", e);
            } catch (NoHttpResponseException e) {
                try {
                    logger.warn("NoHttpResponseException " + e.getMessage());
                    logger.warn("{}", RequestAndResponseData.of(apacheHttpRequest, requestEntityCopy, smartsheetResponse,
                            responseEntityCopy, REQUEST_RESPONSE_SUMMARY));
                    // check to see if the response was empty and this was a POST. All other HTTP methods
                    // will be automatically retried by the http client.
                    // (POST is non-idempotent and is not retried automatically, but is safe for us to retry)
                    if (canRetryRequest && smartsheetRequest.getMethod() == HttpMethod.POST) {
                        if (smartsheetRequest.getEntity() != null) {
                            smartsheetRequest.getEntity().getContent().reset();
                        }
                        continue;
                    }
                } catch (IOException ignore) {
                }
                throw new HttpClientException("Error occurred.", e);
            } catch (IOException e) {
                try {
                    logger.warn("{}", RequestAndResponseData.of(apacheHttpRequest, requestEntityCopy, smartsheetResponse,
                            responseEntityCopy, REQUEST_RESPONSE_SUMMARY));
                } catch (IOException ignore) {
                }
                throw new HttpClientException("Error occurred.", e);
            }
        }
        return smartsheetResponse;
    }
366843
public static <T> T executeJsonResult(HttpUriRequest request,Class<T> clazz){
		return execute(request,JsonResponseHandler.createResponseHandler(clazz));
	}
648738
@Override
    public <TResponse> TResponse post(IReturn<TResponse> request) {
        return send(createUrl(request, HttpMethods.Post), HttpMethods.Post, request, request.getResponseType());
    }
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();
        }
    }
26500
void invoke(HttpRequest request) throws Exception {
    bodyConsumer = null;
    Object invokeResult;
    try {
      args[0] = this.request = request;
      invokeResult = method.invoke(handler, args);
    } catch (InvocationTargetException e) {
      exceptionHandler.handle(e.getTargetException(), request, responder);
      return;
    } catch (Throwable t) {
      exceptionHandler.handle(t, request, responder);
      return;
    }

    if (isStreaming) {
      // Casting guarantee to be succeeded.
      bodyConsumer = (BodyConsumer) invokeResult;
    }
  }
357358
protected String doRequest(HttpRequestBase request) throws IOException {
        for (Map.Entry<Header, String> header : headers.entrySet()) {
            request.setHeader("X-RallyIntegration" + header.getKey().name(), header.getValue());
        }

        return this.executeRequest(request);
    }
440762
public void doWithRequest(
                    final ClientHttpRequest request
                    )
    throws IOException
    {
        HttpHeaders  headers = request.getHeaders();
        headers.setContentType( _mediaType );

        long  size = IoUtil.copy( _input, new OutputStreamWriter( request.getBody() ) );
        headers.setContentLength( size );
    }
792181
public final OAuthCredentialsResponse execute() throws IOException {
    HttpRequestFactory requestFactory = transport.createRequestFactory();
    HttpRequest request =
        requestFactory.buildRequest(usePost ? HttpMethods.POST : HttpMethods.GET, this, null);
    createParameters().intercept(request);
    HttpResponse response = request.execute();
    response.setContentLoggingLimit(0);
    OAuthCredentialsResponse oauthResponse = new OAuthCredentialsResponse();
    UrlEncodedParser.parse(response.parseAsString(), oauthResponse);
    return oauthResponse;
  }
1297722
public static String getBody(ServletRequest request) {
		try {
			return IoUtil.read(request.getReader());
		} catch (IOException e) {
			throw new IORuntimeException(e);
		}
	}
789297
public Response makeRequest(Request request) throws InvalidRequestException {

		logger.debug("Enter HttpRequestClient::makeRequest");

		//prepare request
		RequestBuilder builder = RequestBuilder.create(request.getMethod().value()).setUri(request.constructURL().toString()).setVersion(HttpVersion.HTTP_1_1).setCharset(StandardCharsets.UTF_8);

		//add auth header
		if (request.isRequiresAuthentication()) {
			builder.addHeader(HttpHeaders.AUTHORIZATION, request.getAuthString());
		}

		MethodType method = request.getMethod();
		if (method == MethodType.POST) {
			//add post header
			builder.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

			//add post params
			for (NameValuePair nvp : request.getPostParams()) {
				builder.addParameter(nvp);
			}
		}

		logger.debug("Request URI : " + builder.getUri());
		logger.debug("Http Method : " + builder.getMethod());

		try {
			//make the call
			HttpResponse response = client.execute(builder.build());
			//prepare response
			return new Response(response.getEntity() == null ? null : response.getEntity().getContent(), response.getStatusLine().getStatusCode());
		} catch (IOException e) {
			logger.error("Exception while making httpRequest", e);
			throw new InvalidRequestException(e.getMessage());
		}

	}
780690
public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.debug("Handling HttpServletRequest {}", request);
		response.setContentType(contentType);
		OutputStream output = response.getOutputStream();
		InputStream input = getRequestStream(request);
		int result = ErrorResolver.JsonError.PARSE_ERROR.code;
		int contentLength = 0;
		ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
		try {
			String acceptEncoding = request.getHeader(ACCEPT_ENCODING);
			result = handleRequest0(input, output, acceptEncoding, response, byteOutput);

			contentLength = byteOutput.size();
		} catch (Throwable t) {
			if (StreamEndedException.class.isInstance(t)) {
				logger.debug("Bad request: empty contents!");
			} else {
				logger.error(t.getMessage(), t);
			}
		}
		int httpStatusCode = httpStatusCodeProvider == null ? DefaultHttpStatusCodeProvider.INSTANCE.getHttpStatusCode(result)
				: httpStatusCodeProvider.getHttpStatusCode(result);
		response.setStatus(httpStatusCode);
		response.setContentLength(contentLength);
		byteOutput.writeTo(output);
		output.flush();
	}
898921
@Override
    public Response execute(Request request) throws IOException {
        HttpURLConnection connection = openConnection(request);
        sendRequest(connection, request);
        return readResponse(connection);
    }
1361963
protected Object httpRequest(HttpRequestMethod method, ApiParams apiParams) throws IOException {
        ApiAction action = apiParams.getApiCall();
        String url = apiUrl + "/" + action.toString().toLowerCase();
        String json = GSON.toJson(apiParams, apiParams.getType());
        Map<String, String> params = buildPayload(json);
        Object response = httpClient.executeHttpRequest(url, method, params, handler, customHeaders);
        recordRateLimitInfo(action, method, response);
        return response;
    }