List of usage examples for org.apache.http.protocol BasicHttpContext BasicHttpContext
public BasicHttpContext()
From source file:de.otto.jsonhome.client.HttpJsonHomeClient.java
/** * {@inheritDoc}//from w w w.java2s. c o m */ @Override public JsonHome get(final URI uri) { final HttpGet httpget = new HttpGet(uri); httpget.setHeader("Accept", "application/json"); final BasicHttpContext context = new BasicHttpContext(); final HttpResponse response; try { LOG.info("Getting json-home document {}", uri); response = httpClient.execute(httpget, context); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 404) { LOG.warn("Json-home document {} not found. HTTP status is 404", uri); throw new NotFoundException("Resource " + uri + " not found"); } else if (statusCode >= 400) { final String status = response.getStatusLine().toString(); LOG.warn("Json-home document {} not found: {}", uri, status); throw new HttpStatusException(statusCode, "Failed to load json-home from " + uri + ": Received HTTP status code " + status); } } catch (final IOException e) { LOG.warn("Error getting json-home document {}: {}", uri, e.getMessage()); // in case of an IOException, the connection will be released automatically. throw new JsonHomeClientException("Error getting json-home document " + uri, e); } finally { httpget.reset(); } final HttpEntity entity = response.getEntity(); if (entity != null) { InputStream stream = null; try { stream = entity.getContent(); return new JacksonJsonHomeParser().parse(stream); } catch (final IOException e) { // in case of an IOException, the connection will be released automatically. throw new JsonHomeClientException("Exception caught while getting json-home from " + uri, e); } catch (final RuntimeException e) { httpget.abort(); throw new JsonHomeClientException("Exception caught while getting json-home from " + uri, e); } finally { if (stream != null) try { stream.close(); } catch (IOException e) { /* ignore */ } } } throw new JsonHomeClientException("No content returned when getting json-home resource from " + uri); }
From source file:org.wso2.appserver.integration.tests.webapp.spring.SpringScopeTestCase.java
@Test(groups = "wso2.as", description = "Verfiy Spring Session scope") public void testSpringSessionScope() throws Exception { String endpoint = webAppURL + "/" + webAppMode.getWebAppName() + "/scope/session"; CloseableHttpClient httpClient = HttpClientBuilder.create().build(); CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); HttpGet httpget = new HttpGet(endpoint); HttpResponse response1 = httpClient.execute(httpget, httpContext); String responseMsg1 = new BasicResponseHandler().handleResponse(response1); HttpResponse response2 = httpClient.execute(httpget, httpContext); String responseMsg2 = new BasicResponseHandler().handleResponse(response2); httpClient.close();//from ww w. j a va2 s. co m assertTrue(responseMsg1.equalsIgnoreCase(responseMsg2), "Failed: Responses should be the same"); }
From source file:ui.shared.URLReader.java
public URLReader(String scheme, String host, String path, String query, String key) { cookieStore = new BasicCookieStore(); localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); contents = this.getStringFromPOST(scheme, host, path, query, key); // contents = this.getStringFromURLPOST(scheme, host, path, query, key); }
From source file:org.sonatype.nexus.proxy.storage.remote.httpclient.HttpClientManagerTest.java
@Test public void doNotFollowRedirectsToDirIndex() throws ProtocolException { final RedirectStrategy underTest = httpClientManager.getProxyRepositoryRedirectStrategy(proxyRepository, globalRemoteStorageContext); HttpContext httpContext;/* www. jav a 2 s .com*/ // no location header request = new HttpGet("http://localhost/dir/fileA"); httpContext = new BasicHttpContext(); httpContext.setAttribute(HttpClientRemoteStorage.CONTENT_RETRIEVAL_MARKER_KEY, Boolean.TRUE); when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_OK); assertThat(underTest.isRedirected(request, response, httpContext), is(false)); // redirect to file request = new HttpGet("http://localhost/dir/fileA"); httpContext = new BasicHttpContext(); httpContext.setAttribute(HttpClientRemoteStorage.CONTENT_RETRIEVAL_MARKER_KEY, Boolean.TRUE); when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_MOVED_TEMPORARILY); when(response.getFirstHeader("location")) .thenReturn(new BasicHeader("location", "http://localhost/dir/fileB")); assertThat(underTest.isRedirected(request, response, httpContext), is(true)); // redirect to dir request = new HttpGet("http://localhost/dir"); httpContext = new BasicHttpContext(); httpContext.setAttribute(HttpClientRemoteStorage.CONTENT_RETRIEVAL_MARKER_KEY, Boolean.TRUE); when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_MOVED_TEMPORARILY); when(response.getFirstHeader("location")).thenReturn(new BasicHeader("location", "http://localhost/dir/")); assertThat(underTest.isRedirected(request, response, httpContext), is(false)); }
From source file:org.apache.activemq.artemis.rest.queue.push.UriStrategy.java
protected void initAuthentication() { if (registration.getAuthenticationMechanism() != null) { if (registration.getAuthenticationMechanism().getType() instanceof BasicAuth) { BasicAuth basic = (BasicAuth) registration.getAuthenticationMechanism().getType(); UsernamePasswordCredentials creds = new UsernamePasswordCredentials(basic.getUsername(), basic.getPassword()); AuthScope authScope = new AuthScope(AuthScope.ANY); ((DefaultHttpClient) client).getCredentialsProvider().setCredentials(authScope, creds); localContext = new BasicHttpContext(); // Generate BASIC scheme object and stick it to the local execution context BasicScheme basicAuth = new BasicScheme(); localContext.setAttribute("preemptive-auth", basicAuth); // Add as the first request interceptor ((DefaultHttpClient) client).addRequestInterceptor(new PreemptiveAuth(), 0); executor.setHttpContext(localContext); }//from w ww .j ava2s . c o m } }
From source file:de.mojadev.ohmmarks.virtuohm.VirtuOhmHTTPHandler.java
private void setupHttpIO() { Log.d("Communicator", "Instanciating HTTP Client"); httpIO = AndroidHttpClient.newInstance(USER_AGENT); if (this.cookies == null) { // Setup a cookie store for the httpContext, so we don't have to care about them this.cookies = new BasicCookieStore(); this.httpContext = new BasicHttpContext(); this.httpContext.setAttribute(ClientContext.COOKIE_STORE, this.cookies); }//from w w w. java 2 s . c o m }
From source file:com.flicklib.service.HttpClientSourceLoader.java
@Override public Source post(String url, Map<String, String> parameters, Map<String, String> headers) throws IOException { HttpResponse response = null;/*from w w w . jav a 2 s . com*/ try { LOGGER.info("Loading " + url); HttpPost httpMethod = new HttpPost(url); if (parameters != null && !parameters.isEmpty()) { List<NameValuePair> formparams = new ArrayList<NameValuePair>(); for (Entry<String, String> entry : parameters.entrySet()) { formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } UrlEncodedFormEntity form = new UrlEncodedFormEntity(formparams, "UTF-8"); httpMethod.setEntity(form); } if (headers != null && !headers.isEmpty()) { for (Entry<String, String> entry : headers.entrySet()) { httpMethod.addHeader(entry.getKey(), entry.getValue()); } } HttpContext ctx = new BasicHttpContext(); response = client.execute(httpMethod, ctx); return buildSource(url, response, httpMethod, ctx); } finally { EntityUtils.consume(response.getEntity()); } }
From source file:mixedserver.protocol.jsonrpc.client.HTTPSession.java
public HTTPSession(URI uri) { this.uri = uri; attributes = new Hashtable(); cookieStore = new BasicCookieStore(); localContext = new BasicHttpContext(); // //from w ww. j av a 2 s. c om localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); }
From source file:org.lol.reddit.cache.CacheDownload.java
private void performDownload(final HttpClient httpClient, final HttpRequestBase httpRequest) { if (mInitiator.isJson) httpRequest.setHeader("Accept-Encoding", "gzip"); final HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, mInitiator.getCookies()); final HttpResponse response; final StatusLine status; try {/*from w ww. j av a 2s .c o m*/ if (mCancelled) { mInitiator.notifyFailure(RequestFailureType.CANCELLED, null, null, "Cancelled"); return; } response = httpClient.execute(httpRequest, localContext); status = response.getStatusLine(); } catch (Throwable t) { if (t.getCause() != null && t.getCause() instanceof RedirectException && httpRequest.getURI().getHost().endsWith("reddit.com")) { mInitiator.notifyFailure(RequestFailureType.REDDIT_REDIRECT, t, null, "Unable to open a connection"); } else { mInitiator.notifyFailure(RequestFailureType.CONNECTION, t, null, "Unable to open a connection"); } return; } if (status.getStatusCode() != 200) { mInitiator.notifyFailure(RequestFailureType.REQUEST, null, status, String.format("HTTP error %d (%s)", status.getStatusCode(), status.getReasonPhrase())); return; } if (mCancelled) { mInitiator.notifyFailure(RequestFailureType.CANCELLED, null, null, "Cancelled"); return; } final HttpEntity entity = response.getEntity(); if (entity == null) { mInitiator.notifyFailure(RequestFailureType.CONNECTION, null, status, "Did not receive a valid HTTP response"); return; } final InputStream is; final String mimetype; try { is = entity.getContent(); mimetype = entity.getContentType() == null ? null : entity.getContentType().getValue(); } catch (Throwable t) { t.printStackTrace(); mInitiator.notifyFailure(RequestFailureType.CONNECTION, t, status, "Could not open an input stream"); return; } final NotifyOutputStream cacheOs; final CacheManager.WritableCacheFile cacheFile; if (mInitiator.cache) { try { cacheFile = manager.openNewCacheFile(mInitiator, session, mimetype); cacheOs = cacheFile.getOutputStream(); } catch (IOException e) { e.printStackTrace(); mInitiator.notifyFailure(RequestFailureType.STORAGE, e, null, "Could not access the local cache"); return; } } else { cacheOs = null; cacheFile = null; } final long contentLength = entity.getContentLength(); if (mInitiator.isJson) { final InputStream bis; if (mInitiator.cache) { bis = new BufferedInputStream( new CachingInputStream(is, cacheOs, new CachingInputStream.BytesReadListener() { public void onBytesRead(final long total) { mInitiator.notifyProgress(total, contentLength); } }), 8 * 1024); } else { bis = new BufferedInputStream(is, 8 * 1024); } final JsonValue value; try { value = new JsonValue(bis); synchronized (this) { mInitiator.notifyJsonParseStarted(value, RRTime.utcCurrentTimeMillis(), session, false); } value.buildInThisThread(); } catch (Throwable t) { t.printStackTrace(); mInitiator.notifyFailure(RequestFailureType.PARSE, t, null, "Error parsing the JSON stream"); return; } if (mInitiator.cache && cacheFile != null) { try { mInitiator.notifySuccess(cacheFile.getReadableCacheFile(), RRTime.utcCurrentTimeMillis(), session, false, mimetype); } catch (IOException e) { if (e.getMessage().contains("ENOSPC")) { mInitiator.notifyFailure(RequestFailureType.DISK_SPACE, e, null, "Out of disk space"); } else { mInitiator.notifyFailure(RequestFailureType.STORAGE, e, null, "Cache file not found"); } } } } else { if (!mInitiator.cache) { BugReportActivity.handleGlobalError(mInitiator.context, "Cache disabled for non-JSON request"); return; } try { final byte[] buf = new byte[8 * 1024]; int bytesRead; long totalBytesRead = 0; while ((bytesRead = is.read(buf)) > 0) { totalBytesRead += bytesRead; cacheOs.write(buf, 0, bytesRead); mInitiator.notifyProgress(totalBytesRead, contentLength); } cacheOs.flush(); cacheOs.close(); try { mInitiator.notifySuccess(cacheFile.getReadableCacheFile(), RRTime.utcCurrentTimeMillis(), session, false, mimetype); } catch (IOException e) { if (e.getMessage().contains("ENOSPC")) { mInitiator.notifyFailure(RequestFailureType.DISK_SPACE, e, null, "Out of disk space"); } else { mInitiator.notifyFailure(RequestFailureType.STORAGE, e, null, "Cache file not found"); } } } catch (IOException e) { if (e.getMessage() != null && e.getMessage().contains("ENOSPC")) { mInitiator.notifyFailure(RequestFailureType.STORAGE, e, null, "Out of disk space"); } else { e.printStackTrace(); mInitiator.notifyFailure(RequestFailureType.CONNECTION, e, null, "The connection was interrupted"); } } catch (Throwable t) { t.printStackTrace(); mInitiator.notifyFailure(RequestFailureType.CONNECTION, t, null, "The connection was interrupted"); } } }