List of usage examples for org.apache.http.protocol BasicHttpContext BasicHttpContext
public BasicHttpContext()
From source file:com.netdimensions.client.Client.java
private static BasicHttpContext context(final URI url) { final BasicHttpContext result = new BasicHttpContext(); result.setAttribute(ClientContext.AUTH_CACHE, authCache(url)); return result; }
From source file:net.oauth.client.httpclient4.OAuthSchemeTest.java
@Override public void setUp() throws Exception { { // Get an ephemeral local port number: Socket s = new Socket(); s.bind(null);//w w w .j a v a 2 s. co m port = s.getLocalPort(); s.close(); } server = new Server(port); Context servletContext = new Context(server, "/", Context.SESSIONS); servletContext.addServlet(new ServletHolder(new ProtectedResource()), "/Resource/*"); server.start(); context = new BasicHttpContext(); context.setAttribute(ClientContext.AUTH_SCHEME_PREF, Arrays.asList(OAuthSchemeFactory.SCHEME_NAME)); client = new DefaultHttpClient(); client.getAuthSchemes().register(OAuthSchemeFactory.SCHEME_NAME, new OAuthSchemeFactory()); client.getCredentialsProvider().setCredentials(new AuthScope("localhost", port), new OAuthCredentials(ProtectedResource.ACCESSOR)); }
From source file:com.consol.citrus.http.client.BasicAuthClientHttpRequestFactory.java
/** * Construct the client factory bean with user credentials. *///from ww w.j a v a2 s .c o m public HttpComponentsClientHttpRequestFactory getObject() throws Exception { Assert.notNull(credentials, "User credentials not set properly!"); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient) { @Override protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) { // we have to use preemptive authentication // therefore add some basic auth cache to the local context AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(new HttpHost(authScope.getHost(), authScope.getPort(), "http"), basicAuth); authCache.put(new HttpHost(authScope.getHost(), authScope.getPort(), "https"), basicAuth); BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); return localcontext; } }; if (httpClient instanceof AbstractHttpClient) { ((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials(authScope, credentials); } else { log.warn("Unable to set username password credentials for basic authentication, " + "because nested HttpClient implementation does not support a credentials provider!"); } return requestFactory; }
From source file:com.gs.tools.doc.extractor.core.DownloadManager.java
public byte[] readContentFromGET(String url) throws Exception { byte[] result = null; logger.info("URL: " + url); HttpGet httpGet = new HttpGet(url); HttpResponse response = httpClient.execute(httpGet, new BasicHttpContext()); if (null != response && response.getStatusLine().getStatusCode() == 200) { HttpEntity httpEntity = response.getEntity(); if (null != httpEntity) { // read the response to String InputStream responseStream = httpEntity.getContent(); if (null != responseStream) { BufferedInputStream inputStream = null; ByteArrayOutputStream outputStream = null; try { outputStream = new ByteArrayOutputStream(); inputStream = new BufferedInputStream(responseStream); int count = 0; long totalSize = 0L; int size = 1024; byte[] byteBuff = new byte[size]; while ((count = inputStream.read(byteBuff, 0, size)) >= 0) { totalSize += count; outputStream.write(byteBuff, 0, count); }/* w ww. j a v a 2 s . c o m*/ logger.info("Total Downloaded: " + totalSize + " Byte"); result = outputStream.toByteArray(); } catch (Exception ex) { ex.printStackTrace(); throw ex; } finally { IOUtils.closeQuietly(responseStream); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } } } } return result; }
From source file:org.ocpsoft.redoculous.tests.WebTest.java
/** * Request a resource from the deployed test-application. The context path will be automatically prepended to the * given path./* w ww.j av a 2 s . c o m*/ * <p> * E.g: A path of '/example' will be sent as '/rewrite-test/example' * * @throws Exception */ public HttpAction<HttpDelete> delete(HttpClient client, String path, Header... headers) throws Exception { HttpDelete request = new HttpDelete(getBaseURL() + getContextPath() + path); if (headers != null && headers.length > 0) { request.setHeaders(headers); } HttpContext context = new BasicHttpContext(); HttpResponse response = client.execute(request, context); return new HttpAction<HttpDelete>(client, context, request, response, getBaseURL(), getContextPath()); }
From source file:org.wso2.msf4j.client.ApacheHttpClient.java
@Override public Response execute(Request request, Request.Options options) throws IOException { HttpUriRequest httpUriRequest;/*from ww w .j a va 2 s.c o m*/ HttpContext httpContext = httpContextThreadLocal.get(); if (httpContext == null) { CookieStore cookieStore = new BasicCookieStore(); httpContext = new BasicHttpContext(); httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); httpContextThreadLocal.set(httpContext); } try { httpUriRequest = toHttpUriRequest(request, options); } catch (URISyntaxException e) { throw new IOException("URL '" + request.url() + "' couldn't be parsed into a URI", e); } HttpResponse httpResponse = client.execute(httpUriRequest, httpContext); return toFeignResponse(httpResponse).toBuilder().request(request).build(); }
From source file:io.joynr.messaging.http.HttpMessageSender.java
public void sendMessage(final MessageContainer messageContainer, final FailureAction failureAction) { logger.trace("SEND messageId: {} channelId: {}", messageContainer.getMessageId(), messageContainer.getChannelId()); HttpContext context = new BasicHttpContext(); String channelId = messageContainer.getChannelId(); String messageId = messageContainer.getMessageId(); if (messageContainer.isExpired()) { logger.error("SEND executionQueue.run channelId: {}, messageId: {} TTL expired: ", messageId, messageContainer.getExpiryDate()); failureAction.execute(new JoynrTimeoutException(messageContainer.getExpiryDate())); return;//from ww w . j ava2 s . c o m } // execute http command to send CloseableHttpResponse response = null; String sendUrl = null; try { String serializedMessage = messageContainer.getSerializedMessage(); sendUrl = urlResolver.getSendUrl(messageContainer.getChannelId()); logger.debug("SENDING message channelId: {}, messageId: {} toUrl: {}", new String[] { channelId, messageId, sendUrl }); if (sendUrl == null) { logger.error("SEND executionQueue.run channelId: {}, messageId: {} No channelId found", messageId, messageContainer.getExpiryDate()); failureAction.execute(new JoynrMessageNotSentException("no channelId found")); return; } HttpPost httpPost = httpRequestFactory.createHttpPost(URI.create(sendUrl)); httpPost.addHeader(new BasicHeader(httpConstants.getHEADER_CONTENT_TYPE(), httpConstants.getAPPLICATION_JSON() + ";charset=UTF-8")); httpPost.setEntity(new StringEntity(serializedMessage, "UTF-8")); // Clone the default config Builder requestConfigBuilder = RequestConfig.copy(defaultRequestConfig); requestConfigBuilder.setConnectionRequestTimeout(httpConstants.getSEND_MESSAGE_REQUEST_TIMEOUT()); httpPost.setConfig(requestConfigBuilder.build()); response = httpclient.execute(httpPost, context); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); String statusText = statusLine.getReasonPhrase(); switch (statusCode) { case HttpURLConnection.HTTP_OK: case HttpURLConnection.HTTP_CREATED: logger.debug("SEND to ChannelId: {} messageId: {} completed successfully", channelId, messageId); break; case HttpURLConnection.HTTP_BAD_REQUEST: HttpEntity entity = response.getEntity(); if (entity == null) { logger.error( "SEND to ChannelId: {} messageId: {} completed in error. No further reason found in message body", channelId, messageId); return; } String body = EntityUtils.toString(entity, "UTF-8"); JoynrMessagingError error = objectMapper.readValue(body, JoynrMessagingError.class); JoynrMessagingErrorCode joynrMessagingErrorCode = JoynrMessagingErrorCode .getJoynrMessagingErrorCode(error.getCode()); logger.error(error.toString()); switch (joynrMessagingErrorCode) { case JOYNRMESSAGINGERROR_CHANNELNOTFOUND: failureAction.execute(new JoynrChannelMissingException("Channel does not exist. Status: " + statusCode + " error: " + error.getCode() + "reason:" + error.getReason())); break; default: logger.error("SEND error channelId: {}, messageId: {} url: {} error: {} code: {} reason: {} ", new Object[] { channelId, messageId, sendUrl, statusText, error.getCode(), error.getReason() }); failureAction.execute(new JoynrCommunicationException("Http Error while communicating: " + statusText + body + " error: " + error.getCode() + "reason:" + error.getReason())); break; } break; default: logger.error("SEND to ChannelId: {} messageId: {} - unexpected response code: {} reason: {}", new Object[] { channelId, messageId, statusCode, statusText }); break; } } catch (Exception e) { // An exception occured - this could still be a communication error (e.g Connection refused) logger.error("SEND error channelId: {}, messageId: {} url: {} error: {}", new Object[] { channelId, messageId, sendUrl, e.getMessage() }); failureAction.execute(new JoynrCommunicationException( e.getClass().getName() + "Exception while communicating. error: " + e.getMessage())); } finally { if (response != null) { try { response.close(); } catch (IOException e) { } } } }
From source file:kontrol.HttpUtil.java
public static String getUrlAsString(URI url, int timeout, Locale locale) throws IOException { HttpGet httpget = createHttpGet(url, locale); HttpContext context = new BasicHttpContext(); HttpClient httpClient = getCookielessHttpClient(timeout); HttpResponse httpResponse = httpClient.execute(httpget, context); return IOUtils.toString(httpResponse.getEntity().getContent()); }
From source file:org.sonatype.nexus.testsuite.security.nexus4257.Nexus4257CookieVerificationIT.java
@Test public void testCookieForStateFullClient() throws Exception { setAnonymousAccess(false);/*from w w w.j av a2s .c o m*/ TestContext context = TestContainer.getInstance().getTestContext(); String username = context.getAdminUsername(); String password = context.getPassword(); String url = this.getBaseNexusUrl() + "content/"; URI nexusBaseURI = new URI(url); DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "SomeUAThatWillMakeMeLookStateful/1.0"); final BasicHttpContext localcontext = new BasicHttpContext(); final HttpHost targetHost = new HttpHost(nexusBaseURI.getHost(), nexusBaseURI.getPort(), nexusBaseURI.getScheme()); httpClient.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(username, password)); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); // stateful clients must login first, since other rest urls create no sessions String loginUrl = this.getBaseNexusUrl() + "service/local/authentication/login"; assertThat(executeAndRelease(httpClient, new HttpGet(loginUrl), localcontext), equalTo(200)); // after login check content but make sure only cookie is used httpClient.getCredentialsProvider().clear(); HttpGet getMethod = new HttpGet(url); assertThat(executeAndRelease(httpClient, getMethod, null), equalTo(200)); Cookie sessionCookie = this.getSessionCookie(httpClient.getCookieStore().getCookies()); assertThat("Session Cookie not set", sessionCookie, notNullValue()); httpClient.getCookieStore().clear(); // remove cookies // do not set the cookie, expect failure HttpGet failedGetMethod = new HttpGet(url); assertThat(executeAndRelease(httpClient, failedGetMethod, null), equalTo(401)); // set the cookie expect a 200, If a cookie is set, and cannot be found on the server, the response will fail // with a 401 httpClient.getCookieStore().addCookie(sessionCookie); getMethod = new HttpGet(url); assertThat(executeAndRelease(httpClient, getMethod, null), equalTo(200)); }
From source file:org.zaizi.alfresco.publishing.marklogic.MarkLogicPublishingHelper.java
/** * Build a httpContext from channel properties. * * @param channelProperties the channel properties * @return the http context from channel properties *//*from w w w .ja va 2 s . co m*/ public HttpContext getHttpContextFromChannelProperties(final Map<QName, Serializable> channelProperties) { String markLogicUsername = (String) encryptor.decrypt(PublishingModel.PROP_CHANNEL_USERNAME, channelProperties.get(PublishingModel.PROP_CHANNEL_USERNAME)); String markLogicPassword = (String) encryptor.decrypt(PublishingModel.PROP_CHANNEL_PASSWORD, channelProperties.get(PublishingModel.PROP_CHANNEL_PASSWORD)); UsernamePasswordCredentials creds = new UsernamePasswordCredentials(markLogicUsername, markLogicPassword); HttpContext context = new BasicHttpContext(); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, creds); context.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider); return context; }