public JestResult execute(Action clientRequest) throws IOException { String elasticSearchRestUrl = getRequestURL(getElasticSearchServer(), clientRequest.getURI()); HttpUriRequest request = constructHttpMethod( clientRequest.getRestMethodName(), elasticSearchRestUrl, clientRequest.getData()); // add headers added to action if (!clientRequest.getHeaders().isEmpty()) { for (Entry<String, Object> header : clientRequest.getHeaders().entrySet()) { request.addHeader(header.getKey(), header.getValue() + ""); } } HttpResponse response = httpClient.execute(request); // If head method returns no content, it is added according to response code thanks to // https://github.com/hlassiege if (request.getMethod().equalsIgnoreCase("HEAD")) { if (response.getEntity() == null) { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { response.setEntity(new StringEntity("{\"ok\" : true, \"found\" : true}")); } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { response.setEntity(new StringEntity("{\"ok\" : false, \"found\" : false}")); } } } return deserializeResponse(response, clientRequest.getName(), clientRequest.getPathToResult()); }
private void attachSignature( final HttpUriRequest request, final List<NameValuePair> params, final byte[] content) { final RequestDigestBuffer digest = RequestDigestBuffer.newBuilder(config) .withMethod(request.getMethod()) .withPath(request.getURI().getPath()) .withQueryParams(params) .withTimestamp(Instant.now(Clock.systemUTC()).toEpochMilli()) .build(); final byte[] signature = digest.doFinal(content); for (final Header h : digest.requestHeaders(signature)) { request.addHeader(h); } }
public void executeAsync( final Action clientRequest, final JestResultHandler<JestResult> resultHandler) throws ExecutionException, InterruptedException, IOException { synchronized (this) { if (asyncClient.getStatus() == IOReactorStatus.INACTIVE) { asyncClient.start(); } } String elasticSearchRestUrl = getRequestURL(getElasticSearchServer(), clientRequest.getURI()); final HttpUriRequest request = constructHttpMethod( clientRequest.getRestMethodName(), elasticSearchRestUrl, clientRequest.getData()); // add headers added to action if (!clientRequest.getHeaders().isEmpty()) { for (Entry<String, Object> header : clientRequest.getHeaders().entrySet()) { request.addHeader(header.getKey(), header.getValue() + ""); } } asyncClient.execute( request, new FutureCallback<HttpResponse>() { @Override public void completed(final HttpResponse response) { try { JestResult jestResult = deserializeResponse( response, clientRequest.getName(), clientRequest.getPathToResult()); resultHandler.completed(jestResult); } catch (IOException e) { log.error( "Exception occurred while serializing the response. Exception: " + e.getMessage()); } } @Override public void failed(final Exception ex) { resultHandler.failed(ex); } @Override public void cancelled() {} }); }
private String doSession(String url, String data, int method) throws IOException { HttpClient hcon = null; DataInputStream dis = null; try { hcon = new DefaultHttpClient(); final HttpParams httpParameters = hcon.getParams(); HttpConnectionParams.setSoTimeout(httpParameters, timeout); HttpConnectionParams.setConnectionTimeout(httpParameters, timeout); HttpUriRequest request = getRequest(method, url, data); request.setHeader("Content-Type", "application/json"); request.setHeader("Accept", "application/json"); HttpResponse response = hcon.execute(request); int code = response.getStatusLine().getStatusCode(); if (code != HttpStatus.SC_OK) { throw new IOException("Http response code is: " + code); } StringBuilder responseMessage = new StringBuilder(); InputStreamReader reader = new InputStreamReader(response.getEntity().getContent(), HTTP.UTF_8); try { char[] buffer = new char[4 * 1024]; int readed = 0; while ((readed = reader.read(buffer, 0, buffer.length)) > 0) { responseMessage.append(buffer, 0, readed); } } finally { reader.close(); } return responseMessage.toString(); } finally { try { if (hcon != null) hcon.getConnectionManager().shutdown(); if (dis != null) dis.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } }
public HttpResponse performMultiPartRequest( Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { HttpUriRequest httpRequest = createMultiPartRequest(request, additionalHeaders); addHeaders(httpRequest, additionalHeaders); addHeaders(httpRequest, request.getHeaders()); HttpParams httpParams = httpRequest.getParams(); int timeoutMs = request.getTimeoutMs(); if (timeoutMs != -1) { HttpConnectionParams.setSoTimeout(httpParams, timeoutMs); } /* Make a thread safe connection manager for the client */ HttpClient httpClient = new DefaultHttpClient(httpParams); return httpClient.execute(httpRequest); }
public Either<IOException, HttpResponse> execRequest(HttpUriRequest httpReq, String acceptType) { DefaultHttpClient httpClient = new DefaultHttpClient(); httpReq.setHeader("accept", acceptType); for (Header header : getHeaders()) { httpReq.setHeader(header); } try { HttpResponse resp = httpClient.execute(httpReq); Log.i( TAG, String.format( "%s %s %s => %d", httpReq.getRequestLine().getMethod(), httpReq.getRequestLine().getUri(), httpReq.getParams(), resp.getStatusLine().getStatusCode())); return new Right<IOException, HttpResponse>(resp); } catch (IOException e) { return new Left<IOException, HttpResponse>(e); } }
private <T> T executeRequest(final HttpUriRequest request, final ResponseHandler<T> handler) throws IOException { final CloseableHttpClient client = createClientInstance(); try { final CloseableHttpResponse response = client.execute(request); // Wrap the response in a buffer to facilitate error handlers re-playing the content if the // response // size is smaller than the max allowable buffer if (response.getEntity().getContentLength() >= 0 && response.getEntity().getContentLength() < config.getMaxBufferSize()) { EntityUtils.updateEntity(response, new BufferedHttpEntity(response.getEntity())); } // Explicit check for the authorization status of the API key if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { throw new HyppoAuthException(config); } try { log.debug( "{} - {} : {}", request.getMethod(), request.getURI().getPath(), response.getStatusLine().getStatusCode()); return handler.handleResponse(response); } finally { IOUtils.closeQuietly(response); } } catch (Exception e) { log.error( "{} - {} : FAILED - {}", request.getMethod(), request.getURI().getPath(), e.toString()); throw e; } finally { IOUtils.closeQuietly(client); } }
private String safelyExecuteRequest(String url, int expectedStatus, HttpUriRequest request) { if (hostHeader != null) { request.addHeader(HOST, hostHeader); } try (CloseableHttpResponse response = httpClient.execute(request)) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != expectedStatus) { throw new VerificationException( "Expected status " + expectedStatus + " for " + url + " but was " + statusCode); } return getEntityAsStringAndCloseStream(response); } catch (Exception e) { return throwUnchecked(e, String.class); } }
private static void addHeaders(HttpUriRequest httpRequest, Map<String, String> headers) { for (String key : headers.keySet()) { httpRequest.setHeader(key, headers.get(key)); } }
/** 连接网络读取数据 */ @Override protected <T> void connectWithRetries(AbstractRequest<T> request, InternalResponse response) throws HttpClientException, HttpNetException, HttpServerException { // if(true) { // throw new HttpNetException(NetException.NetworkDisabled); // } // 1. create apache request final HttpUriRequest apacheRequest = createApacheRequest(request); // 2. update http header if (request.getHeaders() != null) { Set<Entry<String, String>> set = request.getHeaders().entrySet(); for (Entry<String, String> en : set) { apacheRequest.setHeader(new BasicHeader(en.getKey(), en.getValue())); } } // 3. try to connect HttpListener<T> listener = request.getHttpListener(); StatisticsListener statistic = response.getStatistics(); int times = 0, maxRetryTimes = request.getMaxRetryTimes(), maxRedirectTimes = request.getMaxRedirectTimes(); boolean retry = true; IOException cause = null; while (retry) { try { cause = null; retry = false; if (request.isCancelledOrInterrupted()) { return; } if (statistic != null) { statistic.onPreConnect(request); } HttpResponse ares = mHttpClient.execute(apacheRequest); if (statistic != null) { statistic.onAfterConnect(request); } // status StatusLine status = ares.getStatusLine(); HttpStatus httpStatus = new HttpStatus(status.getStatusCode(), status.getReasonPhrase()); response.setHttpStatus(httpStatus); // header Header[] headers = ares.getAllHeaders(); if (headers != null) { com.litesuits.http.data.NameValuePair hs[] = new com.litesuits.http.data.NameValuePair[headers.length]; for (int i = 0; i < headers.length; i++) { String name = headers[i].getName(); String value = headers[i].getValue(); if ("Content-Length".equalsIgnoreCase(name)) { response.setContentLength(Long.parseLong(value)); } hs[i] = new com.litesuits.http.data.NameValuePair(name, value); } response.setHeaders(hs); } // data body if (status.getStatusCode() <= 299 || status.getStatusCode() == 600) { // 成功 HttpEntity entity = ares.getEntity(); if (entity != null) { // charset String charSet = getCharsetFromEntity(entity, request.getCharSet()); response.setCharSet(charSet); // is cancelled ? if (request.isCancelledOrInterrupted()) { return; } // length long len = response.getContentLength(); DataParser<T> parser = request.getDataParser(); if (statistic != null) { statistic.onPreRead(request); } parser.readFromNetStream(entity.getContent(), len, charSet); if (statistic != null) { statistic.onAfterRead(request); } response.setReadedLength(parser.getReadedLength()); endEntityViaReflection(entity); } return; } else if (status.getStatusCode() <= 399) { // redirect if (response.getRedirectTimes() < maxRedirectTimes) { // get the location header to find out where to redirect to Header locationHeader = ares.getFirstHeader(Consts.REDIRECT_LOCATION); if (locationHeader != null) { String location = locationHeader.getValue(); if (location != null && location.length() > 0) { if (!location.toLowerCase().startsWith("http")) { URI uri = new URI(request.getFullUri()); URI redirect = new URI(uri.getScheme(), uri.getHost(), location, null); location = redirect.toString(); } response.setRedirectTimes(response.getRedirectTimes() + 1); request.setUri(location); if (HttpLog.isPrint) { HttpLog.i(TAG, "Redirect to : " + location); } if (listener != null) { listener.notifyCallRedirect( request, maxRedirectTimes, response.getRedirectTimes()); } connectWithRetries(request, response); return; } } throw new HttpServerException(httpStatus); } else { throw new HttpServerException(ServerException.RedirectTooMuch); } } else if (status.getStatusCode() <= 499) { // 客户端被拒 throw new HttpServerException(httpStatus); } else if (status.getStatusCode() < 599) { // 服务器有误 throw new HttpServerException(httpStatus); } } catch (IOException e) { cause = e; } catch (NullPointerException e) { // bug in HttpClient 4.0.x, see http://code.google.com/p/android/issues/detail?id=5255 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) { cause = new IOException(e.getMessage()); } else { cause = new IOException(e); } } catch (URISyntaxException e) { throw new HttpClientException(e); } catch (IllegalStateException e) { // for apache http client. if url is illegal, it usually raises an exception as // "IllegalStateException: // Scheme 'xxx' not registered." throw new HttpClientException(e); } catch (SecurityException e) { throw new HttpClientException(e, ClientException.PermissionDenied); } catch (RuntimeException e) { throw new HttpClientException(e); } if (cause != null) { try { if (request.isCancelledOrInterrupted()) { return; } times++; retry = retryHandler.retryRequest( cause, times, maxRetryTimes, mHttpContext, config.getContext()); } catch (InterruptedException e) { e.printStackTrace(); return; } if (retry) { response.setRetryTimes(times); if (HttpLog.isPrint) { HttpLog.i(TAG, "LiteHttp retry request: " + request.getUri()); } if (listener != null) { listener.notifyCallRetry(request, maxRetryTimes, times); } } } } if (cause != null) { throw new HttpNetException(cause); } }
public @Nullable InputStream getAsStream(@Nonnull String account, @Nonnull URI uri) throws CloudException, InternalException { logger.trace("enter - " + AzureMethod.class.getName() + ".get(" + account + "," + uri + ")"); wire.debug("--------------------------------------------------------> " + uri.toASCIIString()); try { HttpClient client = getClient(); HttpUriRequest get = new HttpGet(uri); if (uri.toString().indexOf("/services/images") > -1) { get.addHeader("x-ms-version", "2012-08-01"); } else if (uri.toString().contains("/services/vmimages")) { get.addHeader("x-ms-version", "2014-05-01"); } else { get.addHeader("x-ms-version", "2012-03-01"); } if (strategy != null && strategy.getSendAsHeader()) { get.addHeader(strategy.getHeaderName(), strategy.getRequestId()); } wire.debug(get.getRequestLine().toString()); for (Header header : get.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } HttpResponse response; StatusLine status; try { response = client.execute(get); status = response.getStatusLine(); } catch (IOException e) { logger.error( "get(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage()); throw new CloudException(e); } logger.debug("get(): HTTP Status " + status); Header[] headers = response.getAllHeaders(); wire.debug(status.toString()); for (Header h : headers) { if (h.getValue() != null) { wire.debug(h.getName() + ": " + h.getValue().trim()); } else { wire.debug(h.getName() + ":"); } } if (status.getStatusCode() == HttpServletResponse.SC_NOT_FOUND) { return null; } if (status.getStatusCode() != HttpServletResponse.SC_OK && status.getStatusCode() != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION) { logger.error("get(): Expected OK for GET request, got " + status.getStatusCode()); HttpEntity entity = response.getEntity(); String body; if (entity == null) { throw new AzureException( CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation"); } try { body = EntityUtils.toString(entity); } catch (IOException e) { throw new AzureException( CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } wire.debug(body); AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), body); if (items == null) { return null; } logger.error( "get(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details); throw new AzureException(items); } else { HttpEntity entity = response.getEntity(); if (entity == null) { return null; } InputStream input; try { input = entity.getContent(); } catch (IOException e) { logger.error( "get(): Failed to read response error due to a cloud I/O error: " + e.getMessage()); throw new CloudException(e); } wire.debug("---> Binary Data <---"); return input; } } finally { logger.trace("exit - " + AzureMethod.class.getName() + ".getStream()"); wire.debug( "--------------------------------------------------------> " + uri.toASCIIString()); } }