private HttpResponse getHTTPResponse() throws IOException, NullPointerException { if (fileURI == null) throw new NullPointerException("No file URI specified"); HttpClient client = new DefaultHttpClient(); BasicHttpContext localContext = new BasicHttpContext(); // Clear down the local cookie store every time to make sure we don't have any left over cookies // influencing the test localContext.setAttribute(ClientContext.COOKIE_STORE, null); LOG.info("Mimic WebDriver cookie state: " + mimicWebDriverCookieState); if (mimicWebDriverCookieState) { localContext.setAttribute( ClientContext.COOKIE_STORE, mimicCookieState(driver.manage().getCookies())); } HttpRequestBase requestMethod = httpRequestMethod.getRequestMethod(); requestMethod.setURI(fileURI); HttpParams httpRequestParameters = requestMethod.getParams(); httpRequestParameters.setParameter(ClientPNames.HANDLE_REDIRECTS, followRedirects); requestMethod.setParams(httpRequestParameters); // TODO if post send map of variables, also need to add a post map setter LOG.info("Sending " + httpRequestMethod.toString() + " request for: " + fileURI); return client.execute(requestMethod, localContext); }
public static HttpRequest buildFreeRequest(HttpRequest request) { if (request instanceof HttpRequestBase) { HttpRequestBase httpRequestBase = (HttpRequestBase) request; httpRequestBase.setURI(generateFreeURI(httpRequestBase.getURI())); } return request; }
@Test public void GetRequest() throws URISyntaxException, ClientProtocolException, IOException, ParserConfigurationException, UnsupportedOperationException, SAXException { HttpUriRequest request = new HttpGet(url); URIBuilder uri = new URIBuilder(request.getURI()).addParameter("CountryName", country); ((HttpRequestBase) request).setURI(uri.build()); // Testing headers HttpResponse response = client.execute(request); Header[] headers = response.getAllHeaders(); for (Header head : headers) { System.out.println(head.getName() + "---" + head.getValue()); } System.out.println("================================================"); // Testing response // parsing xml DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(response.getEntity().getContent()); // Printing root doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("string"); Node aNode = nList.item(0); Element element = (Element) aNode; System.out.println(element.getFirstChild()); }
/** * Perform an HTTP Status check and return the response code * * @return * @throws IOException */ public int getHTTPStatusCode() throws IOException { HttpClient client = new DefaultHttpClient(); BasicHttpContext localContext = new BasicHttpContext(); System.out.println("Mimic WebDriver cookie state: " + this.mimicWebDriverCookieState); if (this.mimicWebDriverCookieState) { localContext.setAttribute( ClientContext.COOKIE_STORE, mimicCookieState(this.driver.manage().getCookies())); } HttpRequestBase requestMethod = this.httpRequestMethod.getRequestMethod(); requestMethod.setURI(this.linkToCheck); HttpParams httpRequestParameters = requestMethod.getParams(); httpRequestParameters.setParameter(ClientPNames.HANDLE_REDIRECTS, this.followRedirects); requestMethod.setParams(httpRequestParameters); System.out.println( "Sending " + requestMethod.getMethod() + " request for: " + requestMethod.getURI()); HttpResponse response = client.execute(requestMethod, localContext); System.out.println( "HTTP " + requestMethod.getMethod() + " request status: " + response.getStatusLine().getStatusCode()); return response.getStatusLine().getStatusCode(); }
public Response makeRequest( Methods method, URI uri, HashMap<String, String> requestHeaders, String data) { HttpRequestBase request = null; try { if (method == Methods.GET) { request = new HttpGet(); } else if (method == Methods.POST) { request = new HttpPost(); if (data != null) { ((HttpPost) request).setEntity(new StringEntity(data, "UTF-8")); } } else if (method == Methods.PUT) { request = new HttpPut(); if (data != null) { ((HttpPut) request).setEntity(new StringEntity(data, "UTF-8")); } } else if (method == Methods.DELETE) { request = new HttpDelete(); } } catch (UnsupportedEncodingException e) { logger.log(e); } request.setURI(uri); AndroidHttpClient client = AndroidHttpClient.newInstance(userAgent); if (requestHeaders != null) { for (Map.Entry<String, String> entry : requestHeaders.entrySet()) { request.addHeader(new BasicHeader(entry.getKey(), entry.getValue())); } } HttpResponse response = null; Response retVal = new Response(); retVal.headers = new HashMap<String, String>(); try { response = client.execute(request); } catch (SocketTimeoutException e) { // forget it--we don't care that the user couldn't connect // TODO hand this back as an error to JS } catch (IOException e) { if (!caughtIOException) { caughtIOException = true; logger.log(e); } } catch (Exception e) { logger.log(e); } if (response != null) { retVal.status = response.getStatusLine().getStatusCode(); retVal.body = readContent(response); for (Header header : response.getAllHeaders()) { retVal.headers.put(header.getName(), header.getValue()); } } client.close(); return retVal; }
@Override public void filterAbstractHttpRequest(SubmitContext context, AbstractHttpRequest<?> request) { HttpRequestBase httpMethod = (HttpRequestBase) context.getProperty(BaseHttpRequestTransport.HTTP_METHOD); String strURL = request.getEndpoint(); strURL = PropertyExpander.expandProperties(context, strURL); try { if (StringUtils.hasContent(strURL)) { URI uri = new URI(strURL, request.getSettings().getBoolean(HttpSettings.ENCODED_URLS)); context.setProperty(BaseHttpRequestTransport.REQUEST_URI, uri); httpMethod.setURI(HttpUtils.createUri(uri)); } } catch (Exception e) { SoapUI.logError(e); } }
/** * Internal method to execute the HTTP method given. * * @see AmazonHttpClient#execute(Request, HttpResponseHandler, HttpResponseHandler) * @see AmazonHttpClient#execute(Request, HttpResponseHandler, HttpResponseHandler, * ExecutionContext) */ private <T extends Object> T executeHelper( Request<?> request, HttpResponseHandler<AmazonWebServiceResponse<T>> responseHandler, HttpResponseHandler<AmazonServiceException> errorResponseHandler, ExecutionContext executionContext) throws AmazonClientException, AmazonServiceException { /* * Depending on which response handler we end up choosing to handle the * HTTP response, it might require us to leave the underlying HTTP * connection open, depending on whether or not it reads the complete * HTTP response stream from the HTTP connection, or if delays reading * any of the content until after a response is returned to the caller. */ boolean leaveHttpConnectionOpen = false; // When we release connections, the connection manager leaves them // open so they can be reused. We want to close out any idle // connections so that they don't sit around in CLOSE_WAIT. httpClient.getConnectionManager().closeIdleConnections(30, TimeUnit.SECONDS); if (requestLog.isDebugEnabled()) { requestLog.debug("Sending Request: " + request.toString()); } // Apply whatever request options we know how to handle, such as user-agent. applyRequestData(request); int retryCount = 0; URI redirectedURI = null; HttpEntity entity = null; AmazonServiceException exception = null; // Make a copy of the original request params and headers so that we can // permute it in this loop and start over with the original every time. Map<String, String> originalParameters = new HashMap<String, String>(); originalParameters.putAll(request.getParameters()); Map<String, String> originalHeaders = new HashMap<String, String>(); originalHeaders.putAll(request.getHeaders()); while (true) { if (retryCount > 0) { request.setParameters(originalParameters); request.setHeaders(originalHeaders); } // Sign the request if a signer was provided if (executionContext.getSigner() != null && executionContext.getCredentials() != null) { executionContext.getSigner().sign(request, executionContext.getCredentials()); } HttpRequestBase httpRequest = httpRequestFactory.createHttpRequest(request, config, entity, executionContext); if (httpRequest instanceof HttpEntityEnclosingRequest) { entity = ((HttpEntityEnclosingRequest) httpRequest).getEntity(); } if (redirectedURI != null) { httpRequest.setURI(redirectedURI); } org.apache.http.HttpResponse response = null; try { if (retryCount > 0) { pauseExponentially(retryCount, exception, executionContext.getCustomBackoffStrategy()); if (entity != null) { InputStream content = entity.getContent(); if (content.markSupported()) { content.reset(); } } } exception = null; retryCount++; response = httpClient.execute(httpRequest); if (isRequestSuccessful(response)) { /* * If we get back any 2xx status code, then we know we should * treat the service call as successful. */ leaveHttpConnectionOpen = responseHandler.needsConnectionLeftOpen(); return handleResponse(request, responseHandler, httpRequest, response, executionContext); } else if (isTemporaryRedirect(response)) { /* * S3 sends 307 Temporary Redirects if you try to delete an * EU bucket from the US endpoint. If we get a 307, we'll * point the HTTP method to the redirected location, and let * the next retry deliver the request to the right location. */ Header[] locationHeaders = response.getHeaders("location"); String redirectedLocation = locationHeaders[0].getValue(); log.debug("Redirecting to: " + redirectedLocation); redirectedURI = URI.create(redirectedLocation); httpRequest.setURI(redirectedURI); } else { leaveHttpConnectionOpen = errorResponseHandler.needsConnectionLeftOpen(); exception = handleErrorResponse(request, errorResponseHandler, httpRequest, response); if (!shouldRetry(httpRequest, exception, retryCount)) { throw exception; } } } catch (IOException ioe) { log.warn("Unable to execute HTTP request: " + ioe.getMessage()); if (!shouldRetry(httpRequest, ioe, retryCount)) { throw new AmazonClientException( "Unable to execute HTTP request: " + ioe.getMessage(), ioe); } } finally { /* * Some response handlers need to manually manage the HTTP * connection and will take care of releasing the connection on * their own, but if this response handler doesn't need the * connection left open, we go ahead and release the it to free * up resources. */ if (!leaveHttpConnectionOpen) { try { response.getEntity().getContent().close(); } catch (Throwable t) { } } } } }
@SuppressWarnings("deprecation") @Override public void filterHttpRequest(SubmitContext context, HttpRequestInterface<?> request) { HttpRequestBase httpMethod = (HttpRequestBase) context.getProperty(BaseHttpRequestTransport.HTTP_METHOD); String path = PropertyExpander.expandProperties(context, request.getPath()); StringBuffer query = new StringBuffer(); String encoding = System.getProperty("soapui.request.encoding", StringUtils.unquote(request.getEncoding())); StringToStringMap responseProperties = (StringToStringMap) context.getProperty(BaseHttpRequestTransport.RESPONSE_PROPERTIES); MimeMultipart formMp = "multipart/form-data".equals(request.getMediaType()) && httpMethod instanceof HttpEntityEnclosingRequestBase ? new MimeMultipart() : null; RestParamsPropertyHolder params = request.getParams(); for (int c = 0; c < params.getPropertyCount(); c++) { RestParamProperty param = params.getPropertyAt(c); String value = PropertyExpander.expandProperties(context, param.getValue()); responseProperties.put(param.getName(), value); List<String> valueParts = sendEmptyParameters(request) || (!StringUtils.hasContent(value) && param.getRequired()) ? RestUtils.splitMultipleParametersEmptyIncluded( value, request.getMultiValueDelimiter()) : RestUtils.splitMultipleParameters(value, request.getMultiValueDelimiter()); // skip HEADER and TEMPLATE parameter encoding (TEMPLATE is encoded by // the URI handling further down) if (value != null && param.getStyle() != ParameterStyle.HEADER && param.getStyle() != ParameterStyle.TEMPLATE && !param.isDisableUrlEncoding()) { try { if (StringUtils.hasContent(encoding)) { value = URLEncoder.encode(value, encoding); for (int i = 0; i < valueParts.size(); i++) valueParts.set(i, URLEncoder.encode(valueParts.get(i), encoding)); } else { value = URLEncoder.encode(value); for (int i = 0; i < valueParts.size(); i++) valueParts.set(i, URLEncoder.encode(valueParts.get(i))); } } catch (UnsupportedEncodingException e1) { SoapUI.logError(e1); value = URLEncoder.encode(value); for (int i = 0; i < valueParts.size(); i++) valueParts.set(i, URLEncoder.encode(valueParts.get(i))); } // URLEncoder replaces space with "+", but we want "%20". value = value.replaceAll("\\+", "%20"); for (int i = 0; i < valueParts.size(); i++) valueParts.set(i, valueParts.get(i).replaceAll("\\+", "%20")); } if (param.getStyle() == ParameterStyle.QUERY && !sendEmptyParameters(request)) { if (!StringUtils.hasContent(value) && !param.getRequired()) continue; } switch (param.getStyle()) { case HEADER: for (String valuePart : valueParts) httpMethod.addHeader(param.getName(), valuePart); break; case QUERY: if (formMp == null || !request.isPostQueryString()) { for (String valuePart : valueParts) { if (query.length() > 0) query.append('&'); query.append(URLEncoder.encode(param.getName())); query.append('='); if (StringUtils.hasContent(valuePart)) query.append(valuePart); } } else { try { addFormMultipart( request, formMp, param.getName(), responseProperties.get(param.getName())); } catch (MessagingException e) { SoapUI.logError(e); } } break; case TEMPLATE: try { value = getEncodedValue( value, encoding, param.isDisableUrlEncoding(), request.getSettings().getBoolean(HttpSettings.ENCODED_URLS)); path = path.replaceAll("\\{" + param.getName() + "\\}", value == null ? "" : value); } catch (UnsupportedEncodingException e) { SoapUI.logError(e); } break; case MATRIX: try { value = getEncodedValue( value, encoding, param.isDisableUrlEncoding(), request.getSettings().getBoolean(HttpSettings.ENCODED_URLS)); } catch (UnsupportedEncodingException e) { SoapUI.logError(e); } if (param.getType().equals(XmlBoolean.type.getName())) { if (value.toUpperCase().equals("TRUE") || value.equals("1")) { path += ";" + param.getName(); } } else { path += ";" + param.getName(); if (StringUtils.hasContent(value)) { path += "=" + value; } } break; case PLAIN: break; } } if (request.getSettings().getBoolean(HttpSettings.FORWARD_SLASHES)) path = PathUtils.fixForwardSlashesInPath(path); if (PathUtils.isHttpPath(path)) { try { // URI(String) automatically URLencodes the input, so we need to // decode it first... URI uri = new URI(path, request.getSettings().getBoolean(HttpSettings.ENCODED_URLS)); context.setProperty(BaseHttpRequestTransport.REQUEST_URI, uri); java.net.URI oldUri = httpMethod.getURI(); httpMethod.setURI( HttpUtils.createUri( oldUri.getScheme(), oldUri.getRawUserInfo(), oldUri.getHost(), oldUri.getPort(), oldUri.getRawPath(), uri.getEscapedQuery(), oldUri.getRawFragment())); } catch (Exception e) { SoapUI.logError(e); } } else if (StringUtils.hasContent(path)) { try { java.net.URI oldUri = httpMethod.getURI(); String pathToSet = StringUtils.hasContent(oldUri.getRawPath()) && !"/".equals(oldUri.getRawPath()) ? oldUri.getRawPath() + path : path; java.net.URI newUri = URIUtils.createURI( oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(), pathToSet, oldUri.getQuery(), oldUri.getFragment()); httpMethod.setURI(newUri); context.setProperty( BaseHttpRequestTransport.REQUEST_URI, new URI( newUri.toString(), request.getSettings().getBoolean(HttpSettings.ENCODED_URLS))); } catch (Exception e) { SoapUI.logError(e); } } if (query.length() > 0 && !request.isPostQueryString()) { try { java.net.URI oldUri = httpMethod.getURI(); httpMethod.setURI( URIUtils.createURI( oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(), oldUri.getRawPath(), query.toString(), oldUri.getFragment())); } catch (Exception e) { SoapUI.logError(e); } } if (request instanceof RestRequest) { String acceptEncoding = ((RestRequest) request).getAccept(); if (StringUtils.hasContent(acceptEncoding)) { httpMethod.setHeader("Accept", acceptEncoding); } } if (formMp != null) { // create request message try { if (request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest) { String requestContent = PropertyExpander.expandProperties( context, request.getRequestContent(), request.isEntitizeProperties()); if (StringUtils.hasContent(requestContent)) { initRootPart(request, requestContent, formMp); } } for (Attachment attachment : request.getAttachments()) { MimeBodyPart part = new PreencodedMimeBodyPart("binary"); if (attachment instanceof FileAttachment<?>) { String name = attachment.getName(); if (StringUtils.hasContent(attachment.getContentID()) && !name.equals(attachment.getContentID())) name = attachment.getContentID(); part.setDisposition( "form-data; name=\"" + name + "\"; filename=\"" + attachment.getName() + "\""); } else part.setDisposition("form-data; name=\"" + attachment.getName() + "\""); part.setDataHandler(new DataHandler(new AttachmentDataSource(attachment))); formMp.addBodyPart(part); } MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION); message.setContent(formMp); message.saveChanges(); RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity(message, request); ((HttpEntityEnclosingRequest) httpMethod).setEntity(mimeMessageRequestEntity); httpMethod.setHeader("Content-Type", mimeMessageRequestEntity.getContentType().getValue()); httpMethod.setHeader("MIME-Version", "1.0"); } catch (Throwable e) { SoapUI.logError(e); } } else if (request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest) { if (StringUtils.hasContent(request.getMediaType())) httpMethod.setHeader( "Content-Type", getContentTypeHeader(request.getMediaType(), encoding)); if (request.isPostQueryString()) { try { ((HttpEntityEnclosingRequest) httpMethod).setEntity(new StringEntity(query.toString())); } catch (UnsupportedEncodingException e) { SoapUI.logError(e); } } else { String requestContent = PropertyExpander.expandProperties( context, request.getRequestContent(), request.isEntitizeProperties()); List<Attachment> attachments = new ArrayList<Attachment>(); for (Attachment attachment : request.getAttachments()) { if (attachment.getContentType().equals(request.getMediaType())) { attachments.add(attachment); } } if (StringUtils.hasContent(requestContent) && attachments.isEmpty()) { try { byte[] content = encoding == null ? requestContent.getBytes() : requestContent.getBytes(encoding); ((HttpEntityEnclosingRequest) httpMethod).setEntity(new ByteArrayEntity(content)); } catch (UnsupportedEncodingException e) { ((HttpEntityEnclosingRequest) httpMethod) .setEntity(new ByteArrayEntity(requestContent.getBytes())); } } else if (attachments.size() > 0) { try { MimeMultipart mp = null; if (StringUtils.hasContent(requestContent)) { mp = new MimeMultipart(); initRootPart(request, requestContent, mp); } else if (attachments.size() == 1) { ((HttpEntityEnclosingRequest) httpMethod) .setEntity(new InputStreamEntity(attachments.get(0).getInputStream(), -1)); httpMethod.setHeader( "Content-Type", getContentTypeHeader(request.getMediaType(), encoding)); } if (((HttpEntityEnclosingRequest) httpMethod).getEntity() == null) { if (mp == null) mp = new MimeMultipart(); // init mimeparts AttachmentUtils.addMimeParts(request, attachments, mp, new StringToStringMap()); // create request message MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION); message.setContent(mp); message.saveChanges(); RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity(message, request); ((HttpEntityEnclosingRequest) httpMethod).setEntity(mimeMessageRequestEntity); httpMethod.setHeader( "Content-Type", getContentTypeHeader( mimeMessageRequestEntity.getContentType().getValue(), encoding)); httpMethod.setHeader("MIME-Version", "1.0"); } } catch (Exception e) { SoapUI.logError(e); } } } } }
/** * Internal method to execute the HTTP method given. * * @see AmazonHttpClient#execute(Request, HttpResponseHandler, HttpResponseHandler) * @see AmazonHttpClient#execute(Request, HttpResponseHandler, HttpResponseHandler, * ExecutionContext) */ private <T> Response<T> executeHelper( Request<?> request, HttpResponseHandler<AmazonWebServiceResponse<T>> responseHandler, HttpResponseHandler<AmazonServiceException> errorResponseHandler, ExecutionContext executionContext) throws AmazonClientException, AmazonServiceException { /* * Depending on which response handler we end up choosing to handle the * HTTP response, it might require us to leave the underlying HTTP * connection open, depending on whether or not it reads the complete * HTTP response stream from the HTTP connection, or if delays reading * any of the content until after a response is returned to the caller. */ boolean leaveHttpConnectionOpen = false; AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics(); /* add the service endpoint to the logs. You can infer service name from service endpoint */ awsRequestMetrics.addProperty(Field.ServiceName, request.getServiceName()); awsRequestMetrics.addProperty(Field.ServiceEndpoint, request.getEndpoint()); // Apply whatever request options we know how to handle, such as user-agent. setUserAgent(request); int requestCount = 0; URI redirectedURI = null; HttpEntity entity = null; AmazonClientException retriedException = null; // Make a copy of the original request params and headers so that we can // permute it in this loop and start over with the original every time. Map<String, String> originalParameters = new LinkedHashMap<String, String>(); originalParameters.putAll(request.getParameters()); Map<String, String> originalHeaders = new HashMap<String, String>(); originalHeaders.putAll(request.getHeaders()); final AWSCredentials credentials = executionContext.getCredentials(); Signer signer = null; while (true) { ++requestCount; awsRequestMetrics.setCounter(Field.RequestCount, requestCount); if (requestCount > 1) { // retry request.setParameters(originalParameters); request.setHeaders(originalHeaders); } HttpRequestBase httpRequest = null; org.apache.http.HttpResponse apacheResponse = null; try { // Sign the request if a signer was provided if (signer == null) signer = executionContext.getSignerByURI(request.getEndpoint()); if (signer != null && credentials != null) { awsRequestMetrics.startEvent(Field.RequestSigningTime); try { signer.sign(request, credentials); } finally { awsRequestMetrics.endEvent(Field.RequestSigningTime); } } if (requestLog.isDebugEnabled()) { requestLog.debug("Sending Request: " + request.toString()); } httpRequest = httpRequestFactory.createHttpRequest(request, config, executionContext); if (httpRequest instanceof HttpEntityEnclosingRequest) { entity = ((HttpEntityEnclosingRequest) httpRequest).getEntity(); } if (redirectedURI != null) { httpRequest.setURI(redirectedURI); } if (requestCount > 1) { // retry awsRequestMetrics.startEvent(Field.RetryPauseTime); try { pauseBeforeNextRetry( request.getOriginalRequest(), retriedException, requestCount, config.getRetryPolicy()); } finally { awsRequestMetrics.endEvent(Field.RetryPauseTime); } } if (entity != null) { InputStream content = entity.getContent(); if (requestCount > 1) { // retry if (content.markSupported()) { content.reset(); content.mark(-1); } } else { if (content.markSupported()) { content.mark(-1); } } } captureConnectionPoolMetrics(httpClient.getConnectionManager(), awsRequestMetrics); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(AWSRequestMetrics.class.getSimpleName(), awsRequestMetrics); retriedException = null; awsRequestMetrics.startEvent(Field.HttpRequestTime); try { apacheResponse = httpClient.execute(httpRequest, httpContext); } finally { awsRequestMetrics.endEvent(Field.HttpRequestTime); } if (isRequestSuccessful(apacheResponse)) { awsRequestMetrics.addProperty( Field.StatusCode, apacheResponse.getStatusLine().getStatusCode()); /* * If we get back any 2xx status code, then we know we should * treat the service call as successful. */ leaveHttpConnectionOpen = responseHandler.needsConnectionLeftOpen(); HttpResponse httpResponse = createResponse(httpRequest, request, apacheResponse); T response = handleResponse( request, responseHandler, httpRequest, httpResponse, apacheResponse, executionContext); return new Response<T>(response, httpResponse); } else if (isTemporaryRedirect(apacheResponse)) { /* * S3 sends 307 Temporary Redirects if you try to delete an * EU bucket from the US endpoint. If we get a 307, we'll * point the HTTP method to the redirected location, and let * the next retry deliver the request to the right location. */ Header[] locationHeaders = apacheResponse.getHeaders("location"); String redirectedLocation = locationHeaders[0].getValue(); log.debug("Redirecting to: " + redirectedLocation); redirectedURI = URI.create(redirectedLocation); httpRequest.setURI(redirectedURI); awsRequestMetrics.addProperty( Field.StatusCode, apacheResponse.getStatusLine().getStatusCode()); awsRequestMetrics.addProperty(Field.RedirectLocation, redirectedLocation); awsRequestMetrics.addProperty(Field.AWSRequestID, null); } else { leaveHttpConnectionOpen = errorResponseHandler.needsConnectionLeftOpen(); AmazonServiceException ase = handleErrorResponse(request, errorResponseHandler, httpRequest, apacheResponse); awsRequestMetrics.addProperty(Field.AWSRequestID, ase.getRequestId()); awsRequestMetrics.addProperty(Field.AWSErrorCode, ase.getErrorCode()); awsRequestMetrics.addProperty(Field.StatusCode, ase.getStatusCode()); if (!shouldRetry( request.getOriginalRequest(), httpRequest, ase, requestCount, config.getRetryPolicy())) { throw ase; } // Cache the retryable exception retriedException = ase; /* * Checking for clock skew error again because we don't want to set the * global time offset for every service exception. */ if (RetryUtils.isClockSkewError(ase)) { int timeOffset = parseClockSkewOffset(apacheResponse, ase); SDKGlobalConfiguration.setGlobalTimeOffset(timeOffset); } resetRequestAfterError(request, ase); } } catch (IOException ioe) { if (log.isInfoEnabled()) { log.info("Unable to execute HTTP request: " + ioe.getMessage(), ioe); } awsRequestMetrics.incrementCounter(Field.Exception); awsRequestMetrics.addProperty(Field.Exception, ioe); awsRequestMetrics.addProperty(Field.AWSRequestID, null); AmazonClientException ace = new AmazonClientException("Unable to execute HTTP request: " + ioe.getMessage(), ioe); if (!shouldRetry( request.getOriginalRequest(), httpRequest, ace, requestCount, config.getRetryPolicy())) { throw ace; } // Cache the retryable exception retriedException = ace; resetRequestAfterError(request, ioe); } catch (RuntimeException e) { throw handleUnexpectedFailure(e, awsRequestMetrics); } catch (Error e) { throw handleUnexpectedFailure(e, awsRequestMetrics); } finally { /* * Some response handlers need to manually manage the HTTP * connection and will take care of releasing the connection on * their own, but if this response handler doesn't need the * connection left open, we go ahead and release the it to free * up resources. */ if (!leaveHttpConnectionOpen) { try { if (apacheResponse != null && apacheResponse.getEntity() != null && apacheResponse.getEntity().getContent() != null) { apacheResponse.getEntity().getContent().close(); } } catch (IOException e) { log.warn("Cannot close the response content.", e); } } } } /* end while (true) */ }
/** * Generate and make the necessary HTTP request. * * @return * @throws IOException * @throws ClientProtocolException * @throws URISyntaxException * @throws Exception */ public HttpResponse generateRequest() throws ClientProtocolException, IOException, URISyntaxException { String URL = this.getRequestURL(); // List<NameValuePair> queryParamsNVPair = null; HttpRequestBase request = null; switch (method) { case "GET": request = new HttpGet(URL); for (String headerKey : this.headers.keySet()) { request.addHeader(headerKey, headers.get(headerKey)); } break; case "POST": HttpPost postRequest = new HttpPost(URL); for (String headerKey : this.headers.keySet()) { postRequest.addHeader(headerKey, headers.get(headerKey)); } if (bodyParams != null) { StringEntity requestBodySE = new StringEntity(bodyParams.toString()); requestBodySE.setContentType("application/json"); postRequest.setEntity(requestBodySE); } request = postRequest; break; case "PUT": HttpPut putRequest = new HttpPut(URL); for (String headerKey : this.headers.keySet()) { putRequest.addHeader(headerKey, headers.get(headerKey)); } if (bodyParams != null) { StringEntity requestBodySE = new StringEntity(bodyParams.toString()); System.out.println(requestBodySE.toString()); requestBodySE.setContentEncoding("application/json"); putRequest.setEntity(requestBodySE); } request = putRequest; System.out.println(request.getURI().toString()); break; case "DELETE": request = new HttpDelete(URL); for (String headerKey : this.headers.keySet()) { request.addHeader(headerKey, headers.get(headerKey)); } break; default: break; } if (queryParams != null) { URIBuilder getUriBuilder = new URIBuilder(request.getURI()); Iterator<?> paramKeys = queryParams.keys(); while (paramKeys.hasNext()) { String param = (String) paramKeys.next(); try { getUriBuilder.addParameter(param, queryParams.getString(param)); } catch (JSONException e) { e.printStackTrace(); } } URI getUri = getUriBuilder.build(); ((HttpRequestBase) request).setURI(getUri); } HttpResponse response = sbgClient.execute(request); return response; }