List of usage examples for org.apache.http.client.methods HttpRequestBase getMethod
public abstract String getMethod();
From source file:com.couchbase.cbadmin.client.CouchbaseAdmin.java
private JsonElement getResponseJson(HttpRequestBase req, int expectCode) throws RestApiException, IOException { logger.trace("{} {}", req.getMethod(), req.getURI()); CloseableHttpResponse res = cli.execute(req); try {//from ww w . jav a 2 s . c o m return extractResponse(res, req, expectCode); } finally { if (res.getEntity() != null) { // Ensure the content is completely removed from the stream, // so we can re-use the connection EntityUtils.consumeQuietly(res.getEntity()); } } }
From source file:com.android.idtt.http.HttpHandler.java
private Object sendRequest(HttpRequestBase request) throws HttpException { if (autoResume && isDownloadingFile) { File downloadFile = new File(fileSavePath); long fileLen = 0; if (downloadFile.isFile() && downloadFile.exists()) { fileLen = downloadFile.length(); }/*from w w w . jav a2s .c om*/ if (fileLen > 0) { request.setHeader("RANGE", "bytes=" + fileLen + "-"); } } boolean retry = true; HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler(); while (retry) { IOException exception = null; try { if (request.getMethod().equals(HttpRequest.HttpMethod.GET.toString())) { _getRequestUrl = request.getURI().toString(); } else { _getRequestUrl = null; } if (_getRequestUrl != null) { String result = HttpUtils.sHttpGetCache.get(_getRequestUrl); if (result != null) { // get return result; } } Object responseBody = null; if (!isCancelled()) { HttpResponse response = client.execute(request, context); responseBody = handleResponse(response); } return responseBody; } catch (UnknownHostException e) { exception = e; retry = retryHandler.retryRequest(exception, ++retriedTimes, context); } catch (IOException e) { exception = e; retry = retryHandler.retryRequest(exception, ++retriedTimes, context); } catch (NullPointerException e) { exception = new IOException(e); retry = retryHandler.retryRequest(exception, ++retriedTimes, context); } catch (HttpException e) { throw e; } catch (Exception e) { exception = new IOException(e); retry = retryHandler.retryRequest(exception, ++retriedTimes, context); } finally { if (!retry && exception != null) { throw new HttpException(exception); } } } return null; }
From source file:org.elasticsearch.xpack.security.authc.saml.SamlAuthenticationIT.java
private <T> T execute(CloseableHttpClient client, HttpRequestBase request, HttpContext context, CheckedFunction<HttpResponse, T, IOException> body) throws IOException { final int timeout = (int) TimeValue.timeValueSeconds(90).millis(); RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout) .setConnectTimeout(timeout).setSocketTimeout(timeout).build(); request.setConfig(requestConfig);// w ww. ja v a 2s. c o m logger.info("Execute HTTP " + request.getMethod() + ' ' + request.getURI()); try (CloseableHttpResponse response = SocketAccess.doPrivileged(() -> client.execute(request, context))) { return body.apply(response); } catch (Exception e) { logger.warn(new ParameterizedMessage("HTTP Request [{}] failed", request.getURI()), e); throw e; } }
From source file:de.ub0r.android.websms.connector.common.Utils.java
/** * Get a fresh HTTP-Connection.//from w w w .j a va 2s.c o m * * @param o * {@link HttpOptions} * @return the connection * @throws IOException * IOException */ public static HttpResponse getHttpClient(final HttpOptions o) throws IOException { if (verboseLog) { Log.d(TAG, "HTTPClient URL: " + o.url); } else { Log.d(TAG, "HTTPClient URL: " + o.url.replaceFirst("\\?.*", "")); } if (httpClient == null) { SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", new PlainSocketFactory(), PORT_HTTP)); SocketFactory httpsSocketFactory; if (o.trustAll) { httpsSocketFactory = new FakeSocketFactory(); } else if (o.knownFingerprints != null && o.knownFingerprints.length > 0) { httpsSocketFactory = new FakeSocketFactory(o.knownFingerprints); } else { httpsSocketFactory = SSLSocketFactory.getSocketFactory(); } registry.register(new Scheme("https", httpsSocketFactory, PORT_HTTPS)); HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, o.timeout); HttpConnectionParams.setSoTimeout(params, o.timeout); if (o.maxConnections > 0) { ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRoute() { public int getMaxForRoute(final HttpRoute httproute) { return o.maxConnections; } }); } httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, registry), params); httpClient.addResponseInterceptor(new HttpResponseInterceptor() { public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); Header contentEncodingHeader = entity.getContentEncoding(); if (contentEncodingHeader != null) { HeaderElement[] codecs = contentEncodingHeader.getElements(); for (HeaderElement codec : codecs) { if (codec.getName().equalsIgnoreCase(GZIP)) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } }); } if (o.cookies != null && o.cookies.size() > 0) { final int l = o.cookies.size(); CookieStore cs = httpClient.getCookieStore(); for (int i = 0; i < l; i++) { cs.addCookie(o.cookies.get(i)); } } // . Log.d(TAG, getCookies(httpClient)); HttpRequestBase request; if (o.postData == null) { request = new HttpGet(o.url); } else { HttpPost pr = new HttpPost(o.url); pr.setEntity(o.postData); // . Log.d(TAG, "HTTPClient POST: " + postData); request = pr; } request.addHeader("Accept", "*/*"); request.addHeader(ACCEPT_ENCODING, GZIP); if (o.referer != null) { request.setHeader("Referer", o.referer); if (verboseLog) { Log.d(TAG, "HTTPClient REF: " + o.referer); } } if (o.userAgent != null) { request.setHeader("User-Agent", o.userAgent); if (verboseLog) { Log.d(TAG, "HTTPClient AGENT: " + o.userAgent); } } addHeaders(request, o.headers); if (verboseLog) { Log.d(TAG, "HTTP " + request.getMethod() + " " + request.getURI()); Log.d(TAG, getHeaders(request)); if (request instanceof HttpPost) { Log.d(TAG, ""); Log.d(TAG, ((HttpPost) request).getEntity().getContent()); } } return httpClient.execute(request); }
From source file:cn.isif.util_plus.http.HttpHandler.java
@SuppressWarnings("unchecked") private ResponseInfo<T> sendRequest(HttpRequestBase request) throws HttpException { HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler(); while (true) { if (autoResume && isDownloadingFile) { File downloadFile = new File(fileSavePath); long fileLen = 0; if (downloadFile.isFile() && downloadFile.exists()) { fileLen = downloadFile.length(); }/* w w w . ja va 2 s.com*/ if (fileLen > 0) { request.setHeader("RANGE", "bytes=" + fileLen + "-"); } } boolean retry = true; IOException exception = null; try { requestMethod = request.getMethod(); if (HttpUtils.sHttpCache.isEnabled(requestMethod)) { String result = HttpUtils.sHttpCache.get(requestUrl); if (result != null) { return new ResponseInfo<T>(null, (T) result, true); } } ResponseInfo<T> responseInfo = null; if (!isCancelled()) { HttpResponse response = client.execute(request, context); responseInfo = handleResponse(response); } return responseInfo; } catch (UnknownHostException e) { exception = e; retry = retryHandler.retryRequest(exception, ++retriedCount, context); } catch (IOException e) { exception = e; retry = retryHandler.retryRequest(exception, ++retriedCount, context); } catch (NullPointerException e) { exception = new IOException(e.getMessage()); exception.initCause(e); retry = retryHandler.retryRequest(exception, ++retriedCount, context); } catch (HttpException e) { throw e; } catch (Throwable e) { exception = new IOException(e.getMessage()); exception.initCause(e); retry = retryHandler.retryRequest(exception, ++retriedCount, context); } if (!retry) { throw new HttpException(exception); } } }
From source file:com.drive.student.xutils.http.HttpHandler.java
@SuppressWarnings("unchecked") private com.drive.student.xutils.http.ResponseInfo<T> sendRequest(HttpRequestBase request) throws HttpException { HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler(); while (true) { if (autoResume && isDownloadingFile) { File downloadFile = new File(fileSavePath); long fileLen = 0; if (downloadFile.isFile() && downloadFile.exists()) { fileLen = downloadFile.length(); }/*from w w w . ja va2s . c om*/ if (fileLen > 0) { request.setHeader("RANGE", "bytes=" + fileLen + "-"); } } boolean retry = true; IOException exception = null; try { requestMethod = request.getMethod(); if (HttpUtils.sHttpCache.isEnabled(requestMethod)) { String result = HttpUtils.sHttpCache.get(requestUrl); if (result != null) { return new com.drive.student.xutils.http.ResponseInfo<T>(null, (T) result, true); } } com.drive.student.xutils.http.ResponseInfo<T> responseInfo = null; if (!isCancelled()) { HttpResponse response = client.execute(request, context); responseInfo = handleResponse(response); } return responseInfo; } catch (UnknownHostException e) { exception = e; retry = retryHandler.retryRequest(exception, ++retriedCount, context); } catch (IOException e) { exception = e; retry = retryHandler.retryRequest(exception, ++retriedCount, context); } catch (NullPointerException e) { exception = new IOException(e.getMessage()); exception.initCause(e); retry = retryHandler.retryRequest(exception, ++retriedCount, context); } catch (HttpException e) { throw e; } catch (Throwable e) { exception = new IOException(e.getMessage()); exception.initCause(e); retry = retryHandler.retryRequest(exception, ++retriedCount, context); } if (!retry) { throw new HttpException(exception); } } }
From source file:com.adis.tools.http.HttpHandler.java
@SuppressWarnings("unchecked") private ResponseInfo<T> sendRequest(HttpRequestBase request) throws HttpException { HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler(); while (true) { if (autoResume && isDownloadingFile) { downloadFile = new File(fileSavePath); fileLen = 0;/*from www .j a v a2 s .c o m*/ if (downloadFile.isFile() && downloadFile.exists()) { fileLen = downloadFile.length(); } if (fileLen > 0) { request.setHeader("RANGE", "bytes=" + fileLen + "-"); } } boolean retry = true; IOException exception = null; try { requestMethod = request.getMethod(); if (HttpUtils.sHttpCache.isEnabled(requestMethod)) { String result = HttpUtils.sHttpCache.get(requestUrl); if (result != null) { return new ResponseInfo<T>(null, (T) result, true); } } ResponseInfo<T> responseInfo = null; if (!isCancelled()) { HttpResponse response = client.execute(request, context); responseInfo = handleResponse(response); } return responseInfo; } catch (UnknownHostException e) { exception = e; retry = retryHandler.retryRequest(exception, ++retriedCount, context); } catch (IOException e) { exception = e; retry = retryHandler.retryRequest(exception, ++retriedCount, context); } catch (NullPointerException e) { exception = new IOException(e.getMessage()); exception.initCause(e); retry = retryHandler.retryRequest(exception, ++retriedCount, context); } catch (HttpException e) { throw e; } catch (Throwable e) { exception = new IOException(e.getMessage()); exception.initCause(e); retry = retryHandler.retryRequest(exception, ++retriedCount, context); } if (!retry) { throw new HttpException(exception); } } }
From source file:org.sahli.asciidoc.confluence.publisher.client.http.ConfluenceRestClient.java
private CloseableHttpResponse sendRequestAndFailIfNot20x(HttpRequestBase httpRequest) { CloseableHttpResponse response = sendRequest(httpRequest); StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() < 200 || statusLine.getStatusCode() > 206) { try {//from ww w.j a va 2 s. c o m System.out.println("hoops error occurred"); System.out.println(inputStreamAsString(response.getEntity().getContent())); } catch (IOException e) { e.printStackTrace(); } throw new RuntimeException("Response had not expected status code (between 200 and 206) -> " + statusLine.getStatusCode() + " " + statusLine.getReasonPhrase() + " " + httpRequest.getMethod() + " " + httpRequest.getURI().toString()); } return response; }
From source file:com.mgmtp.perfload.core.client.web.request.HttpRequestHandler.java
/** * Creates the request object./*from w ww . jav a 2 s . c o m*/ * * @param type * the type of the HTTP request (GET, TRACE, DELETE, OPTIONS, HEAD, POST, PUT) * @param uri * the uri * @param parameters * the request parameters * @param body * the request body * @return the request */ protected HttpRequestBase createRequest(final String type, final URI uri, final List<NameValuePair> parameters, final Body body) throws Exception { HttpRequestBase request = HttpMethod.valueOf(type).create(uri); if (!(request instanceof HttpEntityEnclosingRequest)) { // GET, TRACE, DELETE, OPTIONS, HEAD if (!parameters.isEmpty()) { String query = URLEncodedUtils.format(parameters, "UTF-8"); URI requestURI = new URI( uri.getRawQuery() == null ? uri.toString() + '?' + query : uri.toString() + '&' + query); request.setURI(requestURI); } } else { // POST, PUT final HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; if (body != null) { // this only sets the content, header come from the request flow entityRequest.setEntity(new ByteArrayEntity(body.getContent())); } else { checkState(request instanceof HttpPost, "Invalid request: " + request.getMethod() + ". Cannot add post parameters to this kind of request. Please check the request flow."); entityRequest.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8")); } } return request; }
From source file:com.baidubce.http.BceHttpClient.java
/** * Executes the request and returns the result. * * @param request The BCE request to send to the remote server * @param responseClass A response handler to accept a successful response from the remote server * @param responseHandlers A response handler to accept an unsuccessful response from the remote server * * @throws com.baidubce.BceClientException If any errors are encountered on the client while making the * request or handling the response. * @throws com.baidubce.BceServiceException If any errors occurred in BCE while processing the request. */// w w w .j a v a2s . c om public <T extends AbstractBceResponse> T execute(InternalRequest request, Class<T> responseClass, HttpResponseHandler[] responseHandlers) { // Apply whatever request options we know how to handle, such as user-agent. request.addHeader(Headers.USER_AGENT, this.config.getUserAgent()); BceCredentials credentials = config.getCredentials(); if (request.getCredentials() != null) { credentials = request.getCredentials(); } long delayForNextRetryInMillis = 0; for (int attempt = 1;; ++attempt) { HttpRequestBase httpRequest = null; CloseableHttpResponse httpResponse = null; CloseableHttpAsyncClient httpAsyncClient = null; try { // Sign the request if credentials were provided if (credentials != null) { this.signer.sign(request, credentials); } requestLogger.debug("Sending Request: {}", request); httpRequest = this.createHttpRequest(request); HttpContext httpContext = this.createHttpContext(request); if (this.isHttpAsyncPutEnabled && httpRequest.getMethod().equals("PUT")) { httpAsyncClient = this.createHttpAsyncClient(this.createNHttpClientConnectionManager()); httpAsyncClient.start(); Future<HttpResponse> future = httpAsyncClient.execute(HttpAsyncMethods.create(httpRequest), new BasicAsyncResponseConsumer(), httpContext, null); httpResponse = new BceCloseableHttpResponse(future.get()); } else { httpResponse = this.httpClient.execute(httpRequest, httpContext); } HttpUtils.printRequest(httpRequest); BceHttpResponse bceHttpResponse = new BceHttpResponse(httpResponse); T response = responseClass.newInstance(); for (HttpResponseHandler handler : responseHandlers) { if (handler.handle(bceHttpResponse, response)) { break; } } // everything is ok return response; } catch (Exception e) { if (logger.isInfoEnabled()) { logger.info("Unable to execute HTTP request", e); } BceClientException bce; if (e instanceof BceClientException) { bce = (BceClientException) e; } else { bce = new BceClientException("Unable to execute HTTP request", e); } delayForNextRetryInMillis = this.getDelayBeforeNextRetryInMillis(httpRequest, bce, attempt, this.config.getRetryPolicy()); if (delayForNextRetryInMillis < 0) { throw bce; } logger.debug("Retriable error detected, will retry in {} ms, attempt number: {}", delayForNextRetryInMillis, attempt); try { Thread.sleep(delayForNextRetryInMillis); } catch (InterruptedException e1) { throw new BceClientException("Delay interrupted", e1); } if (request.getContent() != null) { request.getContent().restart(); } if (httpResponse != null) { try { HttpEntity entity = httpResponse.getEntity(); if (entity != null && entity.isStreaming()) { final InputStream instream = entity.getContent(); if (instream != null) { instream.close(); } } } catch (IOException e1) { logger.debug("Fail to consume entity.", e1); try { httpResponse.close(); } catch (IOException e2) { logger.debug("Fail to close connection.", e2); } } } } finally { try { if (httpAsyncClient != null) { httpAsyncClient.close(); } } catch (IOException e) { logger.debug("Fail to close HttpAsyncClient", e); } } } }