List of usage examples for org.apache.http.client.methods HttpUriRequest getURI
URI getURI();
From source file:com.mutu.gpstracker.breadcrumbs.DownloadBreadcrumbsTrackTask.java
/** * Retrieve the OAuth Request Token and present a browser to the user to * authorize the token./*from ww w . jav a2s . com*/ */ @Override protected Uri doInBackground(Uri... params) { determineProgressGoal(null); Uri trackUri = null; String trackName = mAdapter.getBreadcrumbsTracks().getValueForItem(mTrack, BreadcrumbsTracks.NAME); HttpEntity responseEntity = null; try { HttpUriRequest request = new HttpGet( "http://api.gobreadcrumbs.com/v1/tracks/" + mTrack.second + "/placemarks.gpx"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } mConsumer.sign(request); if (BreadcrumbsAdapter.DEBUG) { Log.d(TAG, "Execute request: " + request.getURI()); for (Header header : request.getAllHeaders()) { Log.d(TAG, " with header: " + header.toString()); } } HttpResponse response = mHttpclient.execute(request); responseEntity = response.getEntity(); InputStream is = responseEntity.getContent(); InputStream stream = new BufferedInputStream(is, 8192); if (BreadcrumbsAdapter.DEBUG) { stream = XmlCreator.convertStreamToLoggedStream(TAG, stream); } trackUri = importTrack(stream, trackName); } catch (OAuthMessageSignerException e) { handleError(e, mContext.getString(R.string.error_importgpx_xml)); } catch (OAuthExpectationFailedException e) { handleError(e, mContext.getString(R.string.error_importgpx_xml)); } catch (OAuthCommunicationException e) { handleError(e, mContext.getString(R.string.error_importgpx_xml)); } catch (IOException e) { handleError(e, mContext.getString(R.string.error_importgpx_xml)); } finally { if (responseEntity != null) { try { //EntityUtils.consume(responseEntity); responseEntity.consumeContent(); } catch (IOException e) { Log.e(TAG, "Failed to close the content stream", e); } } } return trackUri; }
From source file:org.ovirt.engine.sdk4.internal.HttpConnection.java
/** * Injects HTTP headers in to request// w w w .ja va 2 s . c o m * * @param request */ private void injectHeaders(HttpUriRequest request) { List<Header> updated = excludeNullHeaders(request.getAllHeaders()); if (updated != null && !updated.isEmpty()) { request.setHeaders(updated.toArray(new Header[updated.size()])); } for (NameValuePair nameValuePair : URLEncodedUtils.parse(request.getURI(), HTTP.UTF_8)) { if (nameValuePair.getName().equalsIgnoreCase("all_content")) { request.addHeader("All-Content", nameValuePair.getValue()); } } request.addHeader("Version", "4"); request.addHeader("Content-type", "application/xml"); request.addHeader("User-Agent", "JavaSDK"); request.addHeader("Accept", "application/xml"); request.addHeader("Authorization", "Bearer " + getAccessToken()); }
From source file:com.microsoft.live.UploadRequestTest.java
/** * WinLive 633441: Make sure the query parameters on path get sent to * the HTTP PUT part of the upload./*from ww w . jav a 2s . com*/ */ public void testSendPathQueryParameterToHttpPut() throws Throwable { JSONObject jsonResponseBody = new JSONObject(); jsonResponseBody.put(JsonKeys.UPLOAD_LOCATION, "http://test.com/location"); InputStream responseStream = new ByteArrayInputStream(jsonResponseBody.toString().getBytes()); MockHttpEntity responseEntity = new MockHttpEntity(responseStream); BasicStatusLine ok = new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, ""); final MockHttpResponse uploadLocationResponse = new MockHttpResponse(responseEntity, ok); HttpClient client = new HttpClient() { /** the first request to the client is the upload location request. */ boolean uploadLocationRequest = true; @Override public HttpResponse execute(HttpUriRequest request) throws IOException, ClientProtocolException { if (uploadLocationRequest) { uploadLocationRequest = false; return uploadLocationResponse; } // This is really the only part we care about in this test. // That the 2nd request's uri has foo=bar in the query string. URI uri = request.getURI(); assertEquals("foo=bar&overwrite=choosenewname", uri.getQuery()); // for the test it doesn't matter what it contains, as long as it has valid json. // just return the previous reponse. return uploadLocationResponse; } @Override public HttpResponse execute(HttpUriRequest request, HttpContext context) throws IOException, ClientProtocolException { throw new UnsupportedOperationException(); } @Override public HttpResponse execute(HttpHost target, HttpRequest request) throws IOException, ClientProtocolException { throw new UnsupportedOperationException(); } @Override public <T> T execute(HttpUriRequest arg0, ResponseHandler<? extends T> arg1) throws IOException, ClientProtocolException { throw new UnsupportedOperationException(); } @Override public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException, ClientProtocolException { throw new UnsupportedOperationException(); } @Override public <T> T execute(HttpUriRequest arg0, ResponseHandler<? extends T> arg1, HttpContext arg2) throws IOException, ClientProtocolException { throw new UnsupportedOperationException(); } @Override public <T> T execute(HttpHost arg0, HttpRequest arg1, ResponseHandler<? extends T> arg2) throws IOException, ClientProtocolException { throw new UnsupportedOperationException(); } @Override public <T> T execute(HttpHost arg0, HttpRequest arg1, ResponseHandler<? extends T> arg2, HttpContext arg3) throws IOException, ClientProtocolException { throw new UnsupportedOperationException(); } @Override public ClientConnectionManager getConnectionManager() { throw new UnsupportedOperationException(); } @Override public HttpParams getParams() { throw new UnsupportedOperationException(); } }; LiveConnectSession session = TestUtils.newMockLiveConnectSession(); HttpEntity entity = new MockHttpEntity(); String path = Paths.ME_SKYDRIVE + "?foo=bar"; String filename = "filename"; UploadRequest uploadRequest = new UploadRequest(session, client, path, entity, filename, OverwriteOption.Rename); uploadRequest.execute(); }
From source file:org.apache.brooklyn.entity.dns.geoscaling.GeoscalingWebClient.java
protected HttpResponse sendRequest(HttpUriRequest request, boolean consumeResponse) throws ClientProtocolException, IOException { if (log.isDebugEnabled()) log.debug("Geoscaling request: " + request.getURI() + (request instanceof HttpPost ? " " + ((HttpPost) request).getEntity() : "")); HttpResponse response = httpClient.execute(request); if (log.isDebugEnabled()) log.debug("Geoscaling response: " + response); if (consumeResponse) EntityUtils.consume(response.getEntity()); return response; }
From source file:com.subgraph.vega.internal.http.requests.HttpRequestEngine.java
@Override public IHttpResponse sendRequest(HttpUriRequest request, HttpContext context) throws RequestEngineException { final HttpContext requestContext = (context == null) ? (new BasicHttpContext()) : (context); requestContext.setAttribute(ClientContext.COOKIE_STORE, config.getCookieStore()); Future<IHttpResponse> future = executor .submit(new RequestTask(client, rateLimit, request, requestContext, config, htmlParser)); try {/*from w w w. java2 s .c o m*/ return future.get(); } catch (InterruptedException e) { logger.info("Request " + request.getURI() + " was interrupted before completion"); } catch (ExecutionException e) { throw translateException(request, e.getCause()); } return null; }
From source file:com.corebase.android.framework.http.client.AsyncHttpRequest.java
public AsyncHttpRequest(AbstractHttpClient client, HttpContext context, HttpUriRequest request, CacheParams cacheParams, AsyncHttpResponseHandler responseHandler, Context mycontext) { this.client = client; this.context = context; this.mycontext = mycontext; this.request = request; this.responseHandler = responseHandler; this.cacheParams = cacheParams; this.url = request.getURI().toString(); }
From source file:com.okta.sdk.framework.ApiClient.java
/** * Logs the request method and URI to the console. * @param httpUriRequest {@link HttpUriRequest} Current HTTP URI request object. *//* ww w .ja v a 2 s . com*/ protected void logRequest(HttpUriRequest httpUriRequest) { LOGGER.info(String.format("%s %s", httpUriRequest.getMethod(), httpUriRequest.getURI())); }
From source file:org.everit.authentication.cas.ecm.tests.SampleApp.java
private void casLogin(final SecureHttpClient secureHttpClient, final boolean manipulateTicket) throws Exception { CloseableHttpClient httpClient = secureHttpClient.getHttpClient(); HttpClientContext httpClientContext = secureHttpClient.getHttpClientContext(); String casLoginUrl = CAS_LOGIN_URL + "?" + LOCALE + "&service=" + URLEncoder.encode(helloServiceUrl, StandardCharsets.UTF_8.displayName()); String[] hiddenFormParams = getHiddenParamsFromCasLoginForm(httpClient, httpClientContext, casLoginUrl); // CAS login// w w w . ja va 2 s.c o m HttpPost httpPost = new HttpPost(casLoginUrl); List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("username", secureHttpClient.getPrincipal())); parameters.add(new BasicNameValuePair("password", secureHttpClient.getPrincipal())); parameters.add(new BasicNameValuePair("lt", hiddenFormParams[0])); parameters.add(new BasicNameValuePair("execution", hiddenFormParams[1])); parameters.add(new BasicNameValuePair("_eventId", "submit")); parameters.add(new BasicNameValuePair("submit", "LOGIN")); HttpEntity httpEntity = new UrlEncodedFormEntity(parameters); httpPost.setEntity(httpEntity); HttpResponse httpResponse = httpClient.execute(httpPost, httpClientContext); Assert.assertEquals("No redirect after URL [" + casLoginUrl + "]", HttpServletResponse.SC_MOVED_TEMPORARILY, httpResponse.getStatusLine().getStatusCode()); Header locationHeader = httpResponse.getFirstHeader("Location"); Assert.assertNotNull(locationHeader); String ticketValidationUrl = locationHeader.getValue(); Assert.assertTrue(ticketValidationUrl.startsWith(helloServiceUrl)); String locale = getLocale(httpClientContext); Assert.assertNotNull(locale); EntityUtils.consume(httpResponse.getEntity()); // CAS ticket validation ticketValidationUrl = ticketValidationUrl + "&locale=" + locale; if (manipulateTicket) { ticketValidationUrl = ticketValidationUrl.replace("ticket=", "ticket=X"); } HttpGet httpGet = new HttpGet(ticketValidationUrl); httpResponse = httpClient.execute(httpGet, httpClientContext); if (!manipulateTicket && (secureHttpClient.getPrincipal().equals(CasResourceIdResolver.JOHNDOE) || secureHttpClient.getPrincipal().equals(CasResourceIdResolver.JANEDOE))) { Assert.assertEquals("Failed to access URL [" + ticketValidationUrl + "]", HttpServletResponse.SC_OK, httpResponse.getStatusLine().getStatusCode()); HttpUriRequest currentReq = (HttpUriRequest) httpClientContext.getRequest(); HttpHost currentHost = httpClientContext.getTargetHost(); String currentUrl = (currentReq.getURI().isAbsolute()) ? currentReq.getURI().toString() : (currentHost.toURI() + currentReq.getURI()); Assert.assertEquals(helloServiceUrl, currentUrl); httpEntity = httpResponse.getEntity(); Assert.assertEquals(secureHttpClient.getPrincipal() + "@" + hostname, EntityUtils.toString(httpEntity)); EntityUtils.consume(httpEntity); secureHttpClient.setLoggedIn(true); } else { // Unknown principal (cannot be mapped to a Resource ID) or manipulated ticket Assert.assertEquals("Principal should not be mapped [" + ticketValidationUrl + "]", HttpServletResponse.SC_NOT_FOUND, httpResponse.getStatusLine().getStatusCode()); HttpUriRequest currentReq = (HttpUriRequest) httpClientContext.getRequest(); HttpHost currentHost = httpClientContext.getTargetHost(); String currentUrl = (currentReq.getURI().isAbsolute()) ? currentReq.getURI().toString() : (currentHost.toURI() + currentReq.getURI()); Assert.assertEquals(failedUrl, currentUrl); httpEntity = httpResponse.getEntity(); EntityUtils.consume(httpEntity); secureHttpClient.setLoggedIn(false); } }
From source file:net.oddsoftware.android.html.HttpCache.java
private void download(CacheItem cacheItem) { try {//ww w . jav a 2 s .com // check to see if file exist, if so check etag and last-modified if (cacheItem.mFilename.length() > 0) { File f = new File(cacheItem.mFilename); try { InputStream is = new FileInputStream(f); is.close(); } catch (IOException exc) { // no file, nuke the cache stats cacheItem.mETag = ""; cacheItem.mLastModified = 0; } } else { cacheItem.mFilename = mCacheDirectory + File.separator + UUID.randomUUID().toString() + ".html.gz"; } HttpContext httpContext = new BasicHttpContext(); HttpClient client = createHttpClient(); HttpUriRequest request = createHttpRequest(cacheItem.mUrl, cacheItem.mETag, cacheItem.mLastModified); if (request == null || request.getURI() == null || request.getURI().getHost() == null || request.getURI().getHost().length() == 0) { if (Globals.LOGGING) Log.e(Globals.LOG_TAG, "unable to create http request for url " + cacheItem.mUrl); return; // sadness } HttpResponse response = client.execute(request, httpContext); StatusLine status = response.getStatusLine(); HttpEntity entity = response.getEntity(); if (status.getStatusCode() == 304) { if (Globals.LOGGING) Log.d(Globals.LOG_TAG, "received 304 not modified"); cacheItem.mHitTime = new Date().getTime(); cacheItem.update(mContentResolver); return; } if (status.getStatusCode() == 200) { InputStream inputStream = null; if (entity != null) { inputStream = entity.getContent(); } else { return; } long contentLength = entity.getContentLength(); if (contentLength > MAX_CONTENT_LENGTH) { if (Globals.LOGGING) Log.w(Globals.LOG_TAG, "HttpCache.download item " + cacheItem.mUrl + " content length is too big " + contentLength); return; } Header encodingHeader = entity.getContentEncoding(); boolean encoded = false; if (encodingHeader != null) { if (encodingHeader.getValue().equalsIgnoreCase("gzip")) { inputStream = new GZIPInputStream(inputStream); encoded = true; } else if (encodingHeader.getValue().equalsIgnoreCase("deflate")) { inputStream = new InflaterInputStream(inputStream); encoded = true; } } File tmpFile = File.createTempFile("httpcache", ".html.gz.tmp", mCacheDirectory); OutputStream os = new GZIPOutputStream(new FileOutputStream(tmpFile)); byte[] buffer = new byte[4096]; int count = 0; long fileSize = 0; while ((count = inputStream.read(buffer)) != -1) { os.write(buffer, 0, count); fileSize += count; } inputStream.close(); os.close(); if (!encoded && contentLength > 0 && fileSize != contentLength) { Log.e(Globals.LOG_TAG, "HttpCache.download: content-length: " + contentLength + " but file size: " + fileSize + " aborting"); tmpFile.delete(); return; } tmpFile.renameTo(new File(cacheItem.mFilename)); // if the parse was ok, update these attributes // ETag: "6050003-78e5-4981d775e87c0" Header etagHeader = response.getFirstHeader("ETag"); if (etagHeader != null) { if (etagHeader.getValue().length() < MAX_ETAG_LENGTH) { cacheItem.mETag = etagHeader.getValue(); } else { if (Globals.LOGGING) Log.e(Globals.LOG_TAG, "etag length was too big: " + etagHeader.getValue().length()); } } // Last-Modified: Fri, 24 Dec 2010 00:57:11 GMT Header lastModifiedHeader = response.getFirstHeader("Last-Modified"); if (lastModifiedHeader != null) { try { cacheItem.mLastModified = FeedManager.parseRFC822Date(lastModifiedHeader.getValue()) .getTime(); } catch (ParseException exc) { if (Globals.LOGGING) Log.e(Globals.LOG_TAG, "unable to parse date", exc); } } // Expires: Thu, 01 Dec 1994 16:00:00 GMT Header expiresHeader = response.getFirstHeader("Expires"); if (expiresHeader != null) { try { cacheItem.mExpiresAt = FeedManager.parseRFC822Date(expiresHeader.getValue()).getTime(); } catch (ParseException exc) { if (Globals.LOGGING) Log.e(Globals.LOG_TAG, "unable to parse expires", exc); } } long now = new Date().getTime() + DEFAULT_EXPIRES; if (cacheItem.mExpiresAt < now) { cacheItem.mExpiresAt = now; } HttpUriRequest currentReq = (HttpUriRequest) httpContext .getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost currentHost = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); String currentUrl = currentHost.toURI() + currentReq.getURI(); if (Globals.LOGGING) Log.w(Globals.LOG_TAG, "loaded redirect from " + request.getURI().toString() + " to " + currentUrl); cacheItem.mLastUrl = currentUrl; cacheItem.mHitTime = new Date().getTime(); cacheItem.update(mContentResolver); } } catch (IOException exc) { if (Globals.LOGGING) { Log.e(Globals.LOG_TAG, "error downloading file to cache", exc); } } }
From source file:org.obiba.opal.rest.client.magma.OpalJavaClient.java
private HttpResponse execute(HttpUriRequest msg) throws IOException { msg.addHeader("Accept", "application/x-protobuf, text/html"); authenticate(msg);//from w w w . j av a 2 s . c o m log.debug("{} {}", msg.getMethod(), msg.getURI()); if (log.isTraceEnabled()) { for (Header allHeader : msg.getAllHeaders()) { log.trace(" {} {}", allHeader.getName(), allHeader.getValue()); } } try { return getClient().execute(msg, ctx); } finally { cleanupCache(); } }