List of usage examples for org.apache.http.client.methods HttpRequestBase getURI
public URI getURI()
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 ww . j a va 2 s . c o m*/ 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:com.hp.saas.agm.rest.client.AliRestClient.java
private void writeResponse(ResultInfo result, HttpResponse response, boolean writeBodyAndHeaders, HttpRequestBase method) { OutputStream bodyStream = result.getBodyStream(); StatusLine statusLine = response.getStatusLine(); if (statusLine != null) { result.setReasonPhrase(statusLine.getReasonPhrase()); }// w w w . jav a 2s . com try { result.setLocation(method.getURI().toString()); } catch (Exception e) { throw new RuntimeException(e); } if (writeBodyAndHeaders) { Map<String, String> headersMap = result.getHeaders(); Header[] headers = response.getAllHeaders(); for (Header header : headers) { headersMap.put(header.getName(), header.getValue()); } } result.setHttpStatus(response.getStatusLine().getStatusCode()); Filter filter = new IdentityFilter(result); for (ResponseFilter responseFilter : responseFilters) { filter = responseFilter.applyFilter(filter, response, result); } if (writeBodyAndHeaders && bodyStream != null && response.getStatusLine().getStatusCode() != 204) { try { InputStream responseBody = response.getEntity().getContent(); if (responseBody != null) { copy(responseBody, filter.getOutputStream()); bodyStream.flush(); bodyStream.close(); } } catch (IOException e) { throw new RuntimeException(e); } } }
From source file:com.kappaware.logtrawler.output.httpclient.HttpClient.java
public String exec(HttpRequestBase request, ContentType contentType, String requestData, List<Header> headers) throws HttpClientException { if (headers != null) { for (Header h : headers) { request.setHeader(h);//w w w .ja v a 2 s.c o m } } if (requestData != null) { ((HttpEntityEnclosingRequestBase) request).setEntity(new StringEntity(requestData, contentType)); } CloseableHttpResponse response = null; try { response = httpclient.execute(request); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 404 && this.on404 == On404.NULL_ON_GET && request.getMethod().equals("GET")) { return null; } if (statusCode >= 200 && statusCode < 300) { return getEntity(response); } else { request.getURI(); throw new HttpClientException("Unexpected HTTP Response code", request.getMethod(), request.getURI(), requestData, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(), getEntity(response)); } } catch (Exception e) { if (e instanceof HttpClientException) { throw (HttpClientException) e; } else { throw new HttpClientException("Exception in HTTP Client", request.getMethod(), request.getURI(), requestData, e); } } finally { if (response != null) { try { response.close(); } catch (IOException e) { } } } }
From source file:de.ub0r.android.websms.connector.common.Utils.java
/** * Get a fresh HTTP-Connection.//from w w w .j av a2 s. c om * * @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:com.hp.saas.agm.rest.client.AliRestClient.java
private boolean tryLogin(ResultInfo resultInfo, HttpRequestBase method) { try {/*from w w w . java2 s . c o m*/ login(); return true; } catch (HttpStatusBasedException e) { resultInfo.setHttpStatus(e.getHttpStatus()); resultInfo.setReasonPhrase(e.getReasonPhrase()); try { resultInfo.setLocation(e.getLocation() + " [on-behalf-of: " + method.getURI().toString() + "]"); } catch (Exception e2) { resultInfo.setLocation(e.getLocation() + " [on-behalf-of: " + method.getURI().toString() + "]"); } return false; } }
From source file:com.swisscom.safeconnect.backend.PlumberTask.java
public RawResponse doSyncRequest(HttpRequestBase request) { HttpParams httpParams = new BasicHttpParams(); if (httpTimeout > 0) { HttpConnectionParams.setConnectionTimeout(httpParams, httpTimeout); HttpConnectionParams.setSoTimeout(httpParams, httpTimeout); }//from www . j av a 2 s. co m HttpClient client = null; if (context != null) { Context ctx = context.get(); if (ctx != null) { client = getNewHttpClient(ctx, httpParams); } } if (client == null) { client = new DefaultHttpClient(); } RawResponse response = new RawResponse(); try { HttpResponse httpResponse = client.execute(request); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (BuildConfig.DEBUG) Log.d(Config.TAG, "Request to " + request.getURI().toString() + " --> " + httpResponse.getStatusLine()); // get the body String json = inputStreamToString(httpResponse.getEntity().getContent()); response.status = statusCode; response.body = json; } catch (IOException e) { if (BuildConfig.DEBUG) Log.e(Config.TAG, "Request to " + request.getURI().toString() + " --> FAIL", e); response.status = 0; response.body = null; } return response; }
From source file:alien4cloud.paas.cloudify2.rest.external.RestClientExecutor.java
private <T> T executeRequest(final HttpRequestBase request, final TypeReference<Response<T>> responseTypeReference) throws RestClientException { HttpResponse httpResponse = null;/* w w w .ja v a2 s .c om*/ IOException lastException = null; int numOfTrials = DEFAULT_TRIALS_NUM; if (HttpGet.METHOD_NAME.equals(request.getMethod())) { numOfTrials = GET_TRIALS_NUM; } for (int i = 0; i < numOfTrials; i++) { try { httpResponse = httpClient.execute(request); lastException = null; break; } catch (IOException e) { if (logger.isLoggable(Level.FINER)) { logger.finer("Execute get request to " + request.getURI() + ". try number " + (i + 1) + " out of " + GET_TRIALS_NUM + ", error is " + e.getMessage()); } lastException = e; } } if (lastException != null) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Failed executing " + request.getMethod() + " request to " + request.getURI() + " : " + lastException.getMessage()); } throw MessagesUtils.createRestClientIOException(RestClientMessageKeys.EXECUTION_FAILURE.getName(), lastException, request.getURI()); } String url = request.getURI().toString(); checkForError(httpResponse, url); return getResponseObject(responseTypeReference, httpResponse, url); }
From source file:org.apache.hive.jdbc.TestActivePassiveHA.java
private String sendAuthMethod(HttpRequestBase method, boolean enableAuth, boolean enableCORS) throws Exception { CloseableHttpResponse httpResponse = null; try (CloseableHttpClient client = HttpClients.createDefault();) { // CORS check if (enableCORS) { String origin = "http://example.com"; HttpOptions optionsMethod = new HttpOptions(method.getURI().toString()); optionsMethod.addHeader("Origin", origin); if (enableAuth) { setupAuthHeaders(optionsMethod); }/*from w ww .j av a2s. c om*/ httpResponse = client.execute(optionsMethod); if (httpResponse != null) { StatusLine statusLine = httpResponse.getStatusLine(); if (statusLine != null) { String response = httpResponse.getStatusLine().getReasonPhrase(); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == 200) { Header originHeader = httpResponse.getFirstHeader("Access-Control-Allow-Origin"); assertNotNull(originHeader); assertEquals(origin, originHeader.getValue()); } else { fail("CORS returned: " + statusCode + " Error: " + response); } } else { fail("Status line is null"); } } else { fail("No http Response"); } } if (enableAuth) { setupAuthHeaders(method); } httpResponse = client.execute(method); return EntityUtils.toString(httpResponse.getEntity()); } finally { httpResponse.close(); } }
From source file:com.k42b3.neodym.oauth.Oauth.java
@SuppressWarnings("unchecked") public void signRequest(HttpRequestBase request) throws Exception { // add values HashMap<String, String> values = new HashMap<String, String>(); HashMap<String, String> auth; values.put("oauth_consumer_key", this.provider.getConsumerKey()); values.put("oauth_token", this.token); values.put("oauth_signature_method", provider.getMethod()); values.put("oauth_timestamp", this.getTimestamp()); values.put("oauth_nonce", this.getNonce()); auth = (HashMap<String, String>) values.clone(); // add get vars to values values.putAll(parseQuery(request.getURI().getQuery())); // build base string String baseString = this.buildBaseString(request.getMethod(), request.getURI().toString(), values); // get signature SignatureInterface signature = this.getSignature(); if (signature == null) { throw new Exception("Invalid signature method"); }/*from www . j a v a 2 s. c o m*/ // build signature auth.put("oauth_signature", signature.build(baseString, provider.getConsumerSecret(), this.tokenSecret)); // add header to request request.addHeader("Authorization", "OAuth realm=\"neodym\", " + this.buildAuthString(auth)); }