List of usage examples for org.apache.http.client.protocol ClientContext COOKIE_STORE
String COOKIE_STORE
To view the source code for org.apache.http.client.protocol ClientContext COOKIE_STORE.
Click Source Link
From source file:com.mikecorrigan.bohrium.pubsub.Transaction.java
private int readWrite(HttpEntityEnclosingRequestBase request) { Log.v(TAG, "readWrite"); CookieStore mCookieStore = new BasicCookieStore(); mCookieStore.addCookie(mAuthCookie); DefaultHttpClient httpClient = new DefaultHttpClient(); BasicHttpContext mHttpContext = new BasicHttpContext(); mHttpContext.setAttribute(ClientContext.COOKIE_STORE, mCookieStore); // Encode request body. StringEntity requestEntity;// w ww . j ava2s .c om try { requestEntity = new StringEntity(encode(mRequestBody)); } catch (UnsupportedEncodingException e) { Log.e(TAG, "HTTP encoding failed=" + e); return mStatusCode; } try { final HttpParams getParams = new BasicHttpParams(); HttpClientParams.setRedirecting(getParams, false); request.setParams(getParams); request.setHeader("Content-Type", getMimeType()); request.setEntity(requestEntity); HttpResponse response = httpClient.execute(request, mHttpContext); Log.d(TAG, "status=" + response.getStatusLine()); // Read response body. HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { InputStream is = responseEntity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); sb.append("\n"); } is.close(); mStatusCode = response.getStatusLine().getStatusCode(); mStatusReason = response.getStatusLine().getReasonPhrase(); if (mStatusCode == 200) { mResponseBody = decode(sb.toString()); Log.v(TAG, "mResponseBody=" + sb.toString()); } return mStatusCode; } } catch (IOException e) { Log.e(TAG, "exception=" + e); Log.e(TAG, Log.getStackTraceString(e)); } finally { httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true); } return mStatusCode; }
From source file:com.jayqqaa12.abase.core.AHttp.java
public AHttp configCookieStore(CookieStore cookieStore) { httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); return this; }
From source file:net.paissad.minus.utils.HttpClientUtils.java
/** * Convenience method for sending HTTP requests. * <b><span style="color:red">Note</span></b>: This method is intended to be * used internally, not by end-users./* ww w . j av a 2 s . co m*/ * * @param baseURL - <b>Example</b>: http://minus.com/api * @param parametersBody - The parameters (name => value pairs) to pass to * the request. * @param sessionId - If <tt>null</tt> or empty, then create and use a new * session, otherwise, use the specified session_id (which is * stored in a cookie). * @param requestType * @param additionalRequestHeaders - * @param expectedResponseType * @return The response retrieved from Minus API. * @throws MinusException */ private static MinusHttpResponse sendRequest(final String baseURL, final Map<String, String> parametersBody, final String sessionId, final RequestType requestType, final Header[] additionalRequestHeaders, final ExpectedResponseType expectedResponseType) throws MinusException { DefaultHttpClient client = null; HttpRequestBase request = null; InputStream responseContent = null; boolean errorOccured = false; try { if (requestType == RequestType.GET) { request = new HttpGet(baseURL); if (parametersBody != null && !parametersBody.isEmpty()) { request = appendParametersToRequest(request, parametersBody); } } else if (requestType == RequestType.POST) { UrlEncodedFormEntity encodedEntity = new UrlEncodedFormEntity(getHttpParamsFromMap(parametersBody), HTTP.UTF_8); request = new HttpPost(baseURL); ((HttpPost) request).setEntity(encodedEntity); } else { throw new MinusException("The method (" + requestType + ") is unknown, weird ..."); } request.addHeader(new BasicHeader("User-Agent", APP_USER_AGENT)); if (additionalRequestHeaders != null && additionalRequestHeaders.length > 0) { for (Header aHeader : additionalRequestHeaders) { request.addHeader(aHeader); } } client = new DefaultHttpClient(); client.setHttpRequestRetryHandler(new MinusHttpRequestRetryHandler()); client.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, true); client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); CookieStore cookieStore = new BasicCookieStore(); Cookie sessionCookie = null; if (sessionId != null && !sessionId.trim().isEmpty()) { sessionCookie = new BasicClientCookie2(MINUS_COOKIE_NAME, sessionId); ((BasicClientCookie2) sessionCookie).setPath("/"); ((BasicClientCookie2) sessionCookie).setDomain(MINUS_DOMAIN_NAME); ((BasicClientCookie2) sessionCookie).setVersion(0); cookieStore.addCookie(sessionCookie); } client.setCookieStore(cookieStore); HttpContext localContext = new BasicHttpContext(); // Bind custom cookie store to the local context localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); // Execute the request ... pass local context as a parameter HttpResponse resp = client.execute(request, localContext); // Let's update the cookie have the name 'sessionid' for (Cookie aCookie : client.getCookieStore().getCookies()) { if (aCookie.getName().equals(MINUS_COOKIE_NAME)) { sessionCookie = aCookie; break; } } Object result = null; int statusCode = resp.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { HttpEntity entity = resp.getEntity(); if (entity != null) { if (expectedResponseType == ExpectedResponseType.STRING) { result = EntityUtils.toString(entity); EntityUtils.consume(entity); } else if (expectedResponseType == ExpectedResponseType.HTTP_ENTITY) { result = entity; } } } else { // The response code is not OK. StringBuilder errMsg = new StringBuilder(); errMsg.append("HTTP ").append(requestType).append(" failed => ").append(resp.getStatusLine()); if (request != null) { errMsg.append(" : ").append(request.getURI()); } throw new MinusException(errMsg.toString()); } return new MinusHttpResponse(result, sessionCookie); } catch (Exception e) { errorOccured = true; if (request != null) { request.abort(); } String errMsg = "Error while executing the HTTP " + requestType + " request : " + e.getMessage(); throw new MinusException(errMsg, e); } finally { if (client != null) { // We must not close the client is the expected response is an // InputStream. Indeed, if ever we close the client, we won't be // able to read the response because of SocketException. if (errorOccured) { client.getConnectionManager().shutdown(); } else if (expectedResponseType != ExpectedResponseType.HTTP_ENTITY) { client.getConnectionManager().shutdown(); } } CommonUtils.closeAllStreamsQuietly(responseContent); } }
From source file:com.villemos.ispace.webster.WebsterProducer.java
public void process(Exchange exchange) throws Exception { /** Always ignore authentication protocol errors. */ if (ignoreAuthenticationFailure) { SSLContext sslContext = SSLContext.getInstance("SSL"); // set up a TrustManager that trusts everything sslContext.init(null, new TrustManager[] { new EasyX509TrustManager() }, new SecureRandom()); SchemeRegistry schemeRegistry = new SchemeRegistry(); SSLSocketFactory sf = new SSLSocketFactory(sslContext); Scheme httpsScheme = new Scheme("https", sf, 443); schemeRegistry.register(httpsScheme); SocketFactory sfa = new PlainSocketFactory(); Scheme httpScheme = new Scheme("http", sfa, 80); schemeRegistry.register(httpScheme); HttpParams params = new BasicHttpParams(); ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry); client = new DefaultHttpClient(cm, params); } else {// w w w . j a v a 2 s. c o m client = new DefaultHttpClient(); } String proxyHost = getWebsterEndpoint().getProxyHost(); Integer proxyPort = getWebsterEndpoint().getProxyPort(); if (proxyHost != null && proxyPort != null) { HttpHost proxy = new HttpHost(proxyHost, proxyPort); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } else { ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); client.setRoutePlanner(routePlanner); } /** The target location may demand authentication. We setup preemptive authentication. */ if (getWebsterEndpoint().getAuthenticationUser() != null && getWebsterEndpoint().getAuthenticationPassword() != null) { client.getCredentialsProvider().setCredentials( new AuthScope(getWebsterEndpoint().getDomain(), getWebsterEndpoint().getPort()), new UsernamePasswordCredentials(getWebsterEndpoint().getAuthenticationUser(), getWebsterEndpoint().getAuthenticationPassword())); } /** Set default cookie policy and store. Can be overridden for a specific method using for example; * method.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); */ client.setCookieStore(cookieStore); client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); String uriStr = getWebsterEndpoint().getProtocol() + "://" + getWebsterEndpoint().getDomain() + "/" + getWebsterEndpoint().getPath(); if (getWebsterEndpoint().getPort() != 80) { uriStr += ":" + getWebsterEndpoint().getPort() + "/" + getWebsterEndpoint().getPath(); } /** Break the query into its elements and search for each. */ for (String word : ((String) exchange.getIn().getHeader(SolrOptions.query)).split("\\s+")) { uriStr += "/" + word; URI uri = new URI(uriStr); if (getWebsterEndpoint().getPort() != 80) { target = new HttpHost(getWebsterEndpoint().getDomain(), getWebsterEndpoint().getPort(), getWebsterEndpoint().getProtocol()); } else { target = new HttpHost(getWebsterEndpoint().getDomain()); } localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpUriRequest method = new HttpGet(uri); HttpResponse response = client.execute(target, method, localContext); if (response.getStatusLine().getStatusCode() == 200) { /** Extract result. */ String page = HttpClientConfigurer.readFully(response.getEntity().getContent()); ResultSet set = new ResultSet(); Matcher matcher = pattern.matcher(page); if (matcher.find()) { String result = matcher.group(1).replaceAll("\\<.*?\\>", "").replaceAll("\\s+", " "); /** Create ResultSet*/ InformationObject io = new InformationObject(); io.hasUri = uriStr; io.fromSource = "Webster"; io.hasTitle = "Webster definition of '" + word + "'."; io.ofEntityType = "Definition"; io.ofMimeType = "text/html"; io.withRawText = result; io.score = 20; set.informationobjects.add(io); } matcher = spellPattern.matcher(page); if (matcher.find()) { String result = matcher.group(1); String[] elements = result.split("<li><a href=.*?>"); for (String element : elements) { if (element.trim().equals("") == false) { set.suggestions .add(new Suggestion(word, element.replaceAll("<.*?>", "").trim(), "Webster")); } } } if (exchange.getIn().getHeader(SolrOptions.stream) != null) { for (InformationObject io : set.informationobjects) { Exchange newExchange = new DefaultExchange(endpoint.getCamelContext()); newExchange.getIn().setBody(io); endpoint.getCamelContext().createProducerTemplate() .send((String) exchange.getIn().getHeader(SolrOptions.stream), newExchange); } for (Suggestion suggestion : set.suggestions) { Exchange newExchange = new DefaultExchange(endpoint.getCamelContext()); newExchange.getIn().setBody(suggestion); endpoint.getCamelContext().createProducerTemplate() .send((String) exchange.getIn().getHeader(SolrOptions.stream), newExchange); } } else { exchange.getOut().setBody(set); } } else { HttpEntity entity = response.getEntity(); InputStream instream = entity.getContent(); String page = HttpClientConfigurer.readFully(response.getEntity().getContent()); System.out.println(page); } } }
From source file:org.wso2.carbon.governance.registry.extensions.executors.apistore.RestServiceToAPIExecutor.java
/** * Update the APIM DB for the published API. * * @param api/* ww w . j av a 2 s . c o m*/ * @param serviceName */ private void publishDataToAPIM(GenericArtifact api, String serviceName) throws GovernanceException { if (apimEndpoint == null || apimUsername == null || apimPassword == null) { String msg = "APIManager endpoint URL or credentials are not defined"; log.error(msg); throw new RuntimeException(msg + "API Publish might fail"); } CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); authenticateAPIM(httpContext); String addAPIendpoint = apimEndpoint + "publisher/site/blocks/item-add/ajax/add.jag"; try { // create a post request to addAPI. HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(addAPIendpoint); // Request parameters and other properties. List<NameValuePair> params = new ArrayList<NameValuePair>(); for (String key : api.getAttributeKeys()) { if (log.isDebugEnabled()) { log.error(key + " : " + api.getAttribute(key)); } } if (api.getAttribute("overview_endpointURL") != null && api.getAttribute("overview_endpointURL").isEmpty()) { String msg = "Service Endpoint is a must attribute to create an API definition at the APIStore.Publishing at gateway might fail"; log.warn(msg); } //params.add(new BasicNameValuePair(API_ENDPOINT, api.getAttribute("overview_endpointURL"))); params.add(new BasicNameValuePair(API_ACTION, API_ADD_ACTION)); params.add(new BasicNameValuePair(API_NAME, serviceName)); params.add(new BasicNameValuePair(API_CONTEXT, serviceName)); params.add(new BasicNameValuePair(API_VERSION, api.getAttribute(SERVICE_VERSION))); params.add(new BasicNameValuePair("API_PROVIDER", CarbonContext.getThreadLocalCarbonContext().getUsername())); params.add(new BasicNameValuePair(API_TIER, defaultTier)); params.add(new BasicNameValuePair(API_URI_PATTERN, DEFAULT_URI_PATTERN)); params.add(new BasicNameValuePair(API_URI_HTTP_METHOD, DEFAULT_HTTP_VERB)); params.add(new BasicNameValuePair(API_URI_AUTH_TYPE, DEFAULT_AUTH_TYPE)); params.add(new BasicNameValuePair(API_VISIBLITY, DEFAULT_VISIBILITY)); params.add(new BasicNameValuePair(API_THROTTLING_TIER, apiThrottlingTier)); String[] endPoints = api.getAttributes(Constants.ENDPOINTS_ENTRY); if (endPoints != null && endPoints.length > 0) { List<String> endPointsList = Arrays.asList(endPoints); if (endPointsList.size() > 0) { String endpointConfigJson = "{\"production_endpoints\":{\"url\":\"" + getEnvironmentUrl(endPointsList) + "\",\"config\":null},\"endpoint_type\":\"http\"}"; params.add(new BasicNameValuePair(Constants.ENDPOINT_CONFIG, endpointConfigJson)); } else { String msg = "Endpoint is a must attribute to create an API definition at the APIStore"; throw new GovernanceException(msg); } } else { String msg = "Endpoint is a must attribute to create an API definition at the APIStore"; throw new GovernanceException(msg); } httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); HttpResponse response = httpclient.execute(httppost, httpContext); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException( "Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } } catch (Exception e) { log.error("Error in updating APIM", e); throw new GovernanceException("Error in updating APIM", e); } // after publishing update the lifecycle status //updateStatus(service, serviceName, httpContext); }
From source file:com.benefit.buy.library.http.query.callback.AjaxStatus.java
/** * Return the cookies set by the server. Return values only when source is not from cache (source == NETWORK), * returns empty list otherwise./* w ww. ja v a 2 s. c o m*/ * @return cookies */ public List<Cookie> getCookies() { if (context == null) { return Collections.emptyList(); } CookieStore store = (CookieStore) context.getAttribute(ClientContext.COOKIE_STORE); if (store == null) { return Collections.emptyList(); } return store.getCookies(); }
From source file:com.adavr.http.Client.java
public void clearCookie() { CookieStore store = (CookieStore) localContext.getAttribute(ClientContext.COOKIE_STORE); store.clear(); }
From source file:com.appbase.androidquery.callback.AjaxStatus.java
/** * Return the cookies set by the server. * /*from w w w.jav a2 s. c o m*/ * Return values only when source is not from cache (source == NETWORK), returns empty list otherwise. * * @return cookies */ public List<Cookie> getCookies() { if (context == null) return Collections.emptyList(); CookieStore store = (CookieStore) context.getAttribute(ClientContext.COOKIE_STORE); if (store == null) return Collections.emptyList(); return store.getCookies(); }
From source file:com.villemos.ispace.httpcrawler.HttpAccessor.java
public int poll() throws Exception { /** Always ignore authentication protocol errors. */ if (ignoreAuthenticationFailure) { SSLContext sslContext = SSLContext.getInstance("SSL"); // set up a TrustManager that trusts everything sslContext.init(null, new TrustManager[] { new EasyX509TrustManager() }, new SecureRandom()); SchemeRegistry schemeRegistry = new SchemeRegistry(); SSLSocketFactory sf = new SSLSocketFactory(sslContext); Scheme httpsScheme = new Scheme("https", sf, 443); schemeRegistry.register(httpsScheme); SocketFactory sfa = new PlainSocketFactory(); Scheme httpScheme = new Scheme("http", sfa, 80); schemeRegistry.register(httpScheme); HttpParams params = new BasicHttpParams(); ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry); client = new DefaultHttpClient(cm, params); } else {/*from w ww . j a v a2 s. c om*/ client = new DefaultHttpClient(); } String proxyHost = getHttpCrawlerEndpoint().getProxyHost(); Integer proxyPort = getHttpCrawlerEndpoint().getProxyPort(); if (proxyHost != null && proxyPort != null) { HttpHost proxy = new HttpHost(proxyHost, proxyPort); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } else { ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); client.setRoutePlanner(routePlanner); } /** The target location may demand authentication. We setup preemptive authentication. */ if (getHttpCrawlerEndpoint().getAuthenticationUser() != null && getHttpCrawlerEndpoint().getAuthenticationPassword() != null) { client.getCredentialsProvider().setCredentials( new AuthScope(getHttpCrawlerEndpoint().getDomain(), getHttpCrawlerEndpoint().getPort()), new UsernamePasswordCredentials(getHttpCrawlerEndpoint().getAuthenticationUser(), getHttpCrawlerEndpoint().getAuthenticationPassword())); } /** Set default cookie policy and store. Can be overridden for a specific method using for example; * method.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); */ client.setCookieStore(cookieStore); client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); String uriStr = getHttpCrawlerEndpoint().getProtocol() + "://" + getHttpCrawlerEndpoint().getDomain(); if (getHttpCrawlerEndpoint().getPort() != 80) { uriStr += ":" + getHttpCrawlerEndpoint().getPort() + "" + getHttpCrawlerEndpoint().getPath(); } else { uriStr += getHttpCrawlerEndpoint().getPath(); } URI uri = new URI(uriStr); if (getHttpCrawlerEndpoint().getPort() != 80) { target = new HttpHost(getHttpCrawlerEndpoint().getDomain(), getHttpCrawlerEndpoint().getPort(), getHttpCrawlerEndpoint().getProtocol()); } else { target = new HttpHost(getHttpCrawlerEndpoint().getDomain()); } localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); /** Default boundary is the domain. */ getHttpCrawlerEndpoint().getBoundaries() .add(getHttpCrawlerEndpoint().getProtocol() + "://" + getHttpCrawlerEndpoint().getDomain()); HttpUriRequest method = createInitialRequest(uri); HttpResponse response = client.execute(target, method, localContext); if (response.getStatusLine().getStatusCode() == 200) { processSite(uri, response); } else if (response.getStatusLine().getStatusCode() == 302) { HttpHost target = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); HttpGet get = new HttpGet(target.toURI()); // HttpGet get = new HttpGet("https://om.eo.esa.int/oem/kt/dashboard.php"); /** Read the response fully, to clear it. */ HttpEntity entity = response.getEntity(); HttpClientConfigurer.readFully(entity.getContent()); response = client.execute(target, get, localContext); processSite(uri, response); System.out.println("Final target: " + target); } else { HttpEntity entity = response.getEntity(); InputStream instream = entity.getContent(); System.out.println(HttpClientConfigurer.readFully(instream)); } return 0; }
From source file:org.obiba.opal.rest.client.magma.OpalJavaClient.java
private void createClient() { log.info("Connecting to Opal: {}", opalURI); DefaultHttpClient httpClient = new DefaultHttpClient(); if (keyStore == null) httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); httpClient.getParams().setParameter(ClientPNames.HANDLE_AUTHENTICATION, Boolean.TRUE); httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, Collections.singletonList(OpalAuth.CREDENTIALS_HEADER)); httpClient.getParams().setParameter(ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME, OpalClientConnectionManagerFactory.class.getName()); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(DEFAULT_MAX_ATTEMPT, false)); httpClient.getAuthSchemes().register(OpalAuth.CREDENTIALS_HEADER, new OpalAuthScheme.Factory()); try {/* w w w . ja v a 2 s .c o m*/ httpClient.getConnectionManager().getSchemeRegistry() .register(new Scheme("https", HTTPS_PORT, getSocketFactory())); } catch (NoSuchAlgorithmException | KeyManagementException e) { throw new RuntimeException(e); } client = enableCaching(httpClient); ctx = new BasicHttpContext(); ctx.setAttribute(ClientContext.COOKIE_STORE, new BasicCookieStore()); }