List of usage examples for org.apache.http.impl.client BasicCookieStore BasicCookieStore
public BasicCookieStore()
From source file:com.ibm.twitter.TwitterInsights.java
public TweetList getTweetList(String bookTitle, String bookAuthor) { TweetList returnedTweets = new TweetList(); try {// w ww.j a v a 2 s. c om CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(usernameTwitter, passwordTwitter)); CookieStore cookieStore = new BasicCookieStore(); CookieSpecProvider csf = new CookieSpecProvider() { @Override public CookieSpec create(HttpContext context) { return new DefaultCookieSpec() { @Override public void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException { // Allow all cookies } }; } }; RequestConfig requestConfig = RequestConfig.custom().setCookieSpec("easy").setSocketTimeout(10 * 1000) .setConnectTimeout(10 * 1000).build(); CloseableHttpClient httpClient = HttpClientBuilder.create() .setDefaultCredentialsProvider(credentialsProvider).setDefaultCookieStore(cookieStore) .setDefaultCookieSpecRegistry(RegistryBuilder.<CookieSpecProvider>create() .register(CookieSpecs.DEFAULT, csf).register("easy", csf).build()) .setDefaultRequestConfig(requestConfig).build(); URIBuilder builder = new URIBuilder(); builder.setScheme("https").setHost(baseURLTwitter).setPath("/api/v1/messages/search") .setParameter("q", "\"" + bookTitle + "\"" + " AND " + "\"" + bookAuthor + "\"") .setParameter("size", "5"); URI uri = builder.build(); HttpGet httpGet = new HttpGet(uri); httpGet.setHeader("Content-Type", "text/plain"); HttpResponse httpResponse = httpClient.execute(httpGet); if (httpResponse.getStatusLine().getStatusCode() == 200) { BufferedReader rd = new BufferedReader( new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8")); // Read all the books from the best seller list ObjectMapper mapper = new ObjectMapper(); returnedTweets = mapper.readValue(rd, TweetList.class); } } catch (Exception e) { logger.error("Twitter error: {}", e.getMessage()); } return returnedTweets; }
From source file:de.chaosfisch.google.youtube.upload.metadata.AbstractMetadataService.java
@Override public void activateBrowserfeatures(final Upload upload) throws UnirestException { // Create a local instance of cookie store // Populate cookies if needed final CookieStore cookieStore = new BasicCookieStore(); for (final PersistentCookieStore.SerializableCookie serializableCookie : upload.getAccount() .getSerializeableCookies()) { final BasicClientCookie cookie = new BasicClientCookie(serializableCookie.getCookie().getName(), serializableCookie.getCookie().getValue()); cookie.setDomain(serializableCookie.getCookie().getDomain()); cookieStore.addCookie(cookie);//from w ww . jav a 2 s . c om } final HttpClient client = HttpClientBuilder.create().useSystemProperties() .setDefaultCookieStore(cookieStore).build(); Unirest.setHttpClient(client); final HttpResponse<String> response = Unirest.get(String.format(VIDEO_EDIT_URL, upload.getVideoid())) .asString(); changeMetadata(response.getBody(), upload); final RequestConfig clientConfig = RequestConfig.custom().setConnectTimeout(600000).setSocketTimeout(600000) .build(); Unirest.setHttpClient(HttpClientBuilder.create().setDefaultRequestConfig(clientConfig).build()); }
From source file:edu.isi.misd.tagfiler.client.JakartaClient.java
/** * Initialize the HTTP client//w ww . ja v a 2 s . c om * * @param connections * the maximum number of HTTP connections * @param socketBufferSize * the socket buffer size * @param socketTimeout * the socket buffer timeout */ private void init(int maxConnections, int socketBufferSize, int socketTimeout) throws Throwable { TrustManager easyTrustManager = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { // Oh, I am easy! } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { if (chain != null) { for (int i = 0; i < chain.length; i++) { chain[i].checkValidity(); } } } public X509Certificate[] getAcceptedIssuers() { return null; } }; SSLContext sslcontext = SSLContext.getInstance("SSL"); sslcontext.init(null, new TrustManager[] { easyTrustManager }, null); SSLSocketFactory sf = new SSLSocketFactory(sslcontext); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); BasicHttpParams params = new BasicHttpParams(); params.setParameter("http.protocol.handle-redirects", false); params.setParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, socketBufferSize); params.setParameter(CoreConnectionPNames.SO_TIMEOUT, socketTimeout); // enable parallelism ConnPerRouteBean connPerRoute = new ConnPerRouteBean(maxConnections); ConnManagerParams.setMaxTotalConnections(params, maxConnections >= 2 ? maxConnections : 2); ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute); SchemeRegistry schemeRegistry = new SchemeRegistry(); Scheme sch = new Scheme("https", sf, 443); schemeRegistry.register(sch); //schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); httpclient = new DefaultHttpClient(cm, params); BasicCookieStore cookieStore = new BasicCookieStore(); httpclient.setCookieStore(cookieStore); }
From source file:org.nextlets.erc.defaults.http.ERCHttpInvokerImpl.java
private CookieStore toCookieStore(URI uri, CookieManager cm) { CookieStore cs = new BasicCookieStore(); for (HttpCookie hc : cm.getCookieStore().getCookies()) { cs.addCookie(toCookie(uri, hc)); }/*from w ww. java 2 s. c o m*/ return cs; }
From source file:cn.code.notes.gtask.remote.GTaskClient.java
private boolean loginGtask(String authToken) { int timeoutConnection = 10000; int timeoutSocket = 15000; HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); mHttpClient = new DefaultHttpClient(httpParameters); BasicCookieStore localBasicCookieStore = new BasicCookieStore(); mHttpClient.setCookieStore(localBasicCookieStore); HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); // login gtask try {//from w w w.j av a 2s . co m String loginUrl = mGetUrl + "?auth=" + authToken; HttpGet httpGet = new HttpGet(loginUrl); HttpResponse response = null; response = mHttpClient.execute(httpGet); // get the cookie now List<Cookie> cookies = mHttpClient.getCookieStore().getCookies(); boolean hasAuthCookie = false; for (Cookie cookie : cookies) { if (cookie.getName().contains("GTL")) { hasAuthCookie = true; } } if (!hasAuthCookie) { Log.w(TAG, "it seems that there is no auth cookie"); } // get the client version String resString = getResponseContent(response.getEntity()); String jsBegin = "_setup("; String jsEnd = ")}</script>"; int begin = resString.indexOf(jsBegin); int end = resString.lastIndexOf(jsEnd); String jsString = null; if (begin != -1 && end != -1 && begin < end) { jsString = resString.substring(begin + jsBegin.length(), end); } JSONObject js = new JSONObject(jsString); mClientVersion = js.getLong("v"); } catch (JSONException e) { Log.e(TAG, e.toString()); e.printStackTrace(); return false; } catch (Exception e) { // simply catch all exceptions Log.e(TAG, "httpget gtask_url failed"); return false; } return true; }
From source file:com.normalexception.app.rx8club.html.LoginFactory.java
/** * Initialize the client, cookie store, and context *//*from w w w . j av a2s .co m*/ private void initializeClientInformation() { Log.d(TAG, "Initializing Client..."); /* Log.d(TAG, "Creating Custom Cache Configuration"); CacheConfig cacheConfig = CacheConfig.custom() .setMaxCacheEntries(1000) .setMaxObjectSize(8192) .build(); */ Log.d(TAG, "Creating Custom Request Configuration"); RequestConfig rConfig = RequestConfig.custom().setCircularRedirectsAllowed(true) .setConnectionRequestTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build(); cookieStore = new BasicCookieStore(); httpContext = new BasicHttpContext(); Log.d(TAG, "Building Custom HTTP Client"); HttpClientBuilder httpclientbuilder = HttpClients.custom(); //httpclientbuilder.setCacheConfig(cacheConfig); httpclientbuilder.setDefaultRequestConfig(rConfig); httpclientbuilder.setDefaultCookieStore(cookieStore); Log.d(TAG, "Connection Manager Initializing"); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); cm.setMaxTotal(200); cm.setDefaultMaxPerRoute(20); httpclientbuilder.setConnectionManager(cm); Log.d(TAG, "Enable GZIP Compression"); httpclientbuilder.addInterceptorLast(new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (!request.containsHeader("Accept-Encoding")) { request.addHeader("Accept-Encoding", "gzip"); } } }); httpclientbuilder.addInterceptorLast(new HttpResponseInterceptor() { public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } } }); // Follow Redirects Log.d(TAG, "Registering Redirect Strategy"); httpclientbuilder.setRedirectStrategy(new RedirectStrategy()); // Setup retry handler Log.d(TAG, "Registering Retry Handler"); httpclientbuilder.setRetryHandler(new RetryHandler()); // Setup KAS Log.d(TAG, "Registering Keep Alive Strategy"); httpclientbuilder.setKeepAliveStrategy(new KeepAliveStrategy()); httpclient = httpclientbuilder.build(); //httpclient.log.enableDebug( // MainApplication.isHttpClientLogEnabled()); isInitialized = true; }
From source file:org.wso2.carbon.governance.registry.extensions.executors.apistore.ServiceToAPIExecutor.java
/** * Update the APIM DB for the published API. * * @param resource//from w w w. ja va 2 s . c o m * @param serviceName */ private boolean publishDataToAPIM(Resource resource, String serviceName) throws GovernanceException { boolean valid = true; if (apimEndpoint == null || apimUsername == null || apimPassword == null || apimEnv == null) { throw new GovernanceException(ExecutorConstants.APIM_LOGIN_UNDEFINED); } CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); // APIUtils apiUtils = new APIUtils(); APIUtils.authenticateAPIM(httpContext, apimEndpoint, apimUsername, apimPassword); String addAPIendpoint = apimEndpoint + Constants.APIM_ENDPOINT; 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>(); String[] endPoints = artifact.getAttributes(Constants.ENDPOINTS_ENTRY); if (endPoints == null || endPoints.length == 0) { String msg = "Service Endpoint is a must attribute to create an API definition at the APIStore"; throw new GovernanceException(msg); } List<String> endPointsList = Arrays.asList(endPoints); if (endPointsList == null) { String msg = "Service Endpoint is a must attribute to create an API definition at the APIStore"; throw new GovernanceException(msg); } addParameters(params, resource, serviceName); LOG.info(new UrlEncodedFormEntity(params, Constants.UTF_8_ENCODE)); ResponseAPIM responseAPIM = APIUtils.callAPIMToPublishAPI(httpclient, httppost, params, httpContext); if (responseAPIM.getError().equalsIgnoreCase(Constants.TRUE_CONSTANT)) { LOG.error(responseAPIM.getMessage()); throw new GovernanceException("Error occurred while adding the api to API Manager."); } } catch (Exception e) { throw new GovernanceException(e.getMessage(), e); } return valid; }
From source file:microsoft.exchange.webservices.data.HttpClientWebRequest.java
/** * Prepare asynchronous connection./*ww w . ja v a 2 s .c om*/ * * @throws microsoft.exchange.webservices.data.EWSHttpException throws EWSHttpException */ public void prepareAsyncConnection() throws EWSHttpException { try { //ssl config HttpClientBuilder builder = HttpClients.custom(); builder.setConnectionManager(this.httpClientConnMng); builder.setSchemePortResolver(new DefaultSchemePortResolver()); EwsSSLProtocolSocketFactory factory = EwsSSLProtocolSocketFactory.build(trustManger); builder.setSSLSocketFactory(factory); builder.setSslcontext(factory.getContext()); //create the cookie store if (cookieStore == null) { cookieStore = new BasicCookieStore(); } builder.setDefaultCookieStore(cookieStore); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new NTCredentials(getUserName(), getPassword(), "", getDomain())); builder.setDefaultCredentialsProvider(credsProvider); //fix socket config SocketConfig sc = SocketConfig.custom().setSoTimeout(getTimeout()).build(); builder.setDefaultSocketConfig(sc); RequestConfig.Builder rcBuilder = RequestConfig.custom(); rcBuilder.setConnectionRequestTimeout(getTimeout()); rcBuilder.setConnectTimeout(getTimeout()); rcBuilder.setSocketTimeout(getTimeout()); // fix issue #144 + #160: if we used NTCredentials from above: these are NT credentials ArrayList<String> authPrefs = new ArrayList<String>(); authPrefs.add(AuthSchemes.NTLM); rcBuilder.setTargetPreferredAuthSchemes(authPrefs); // builder.setDefaultRequestConfig(rcBuilder.build()); //HttpClientParams.setRedirecting(client.getParams(), isAllowAutoRedirect()); by default it follows redirects //create the client and execute requests client = builder.build(); httpPostReq = new HttpPost(getUrl().toString()); response = client.execute(httpPostReq); } catch (IOException e) { client = null; httpPostReq = null; throw new EWSHttpException("Unable to open connection to " + this.getUrl()); } catch (Exception e) { client = null; httpPostReq = null; e.printStackTrace(); throw new EWSHttpException("SSL problem " + this.getUrl()); } }
From source file:org.everit.osgi.authentication.http.session.tests.SessionAuthenticationTestComponent.java
@Test public void testAccessHelloPage() throws Exception { CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); long sessionResourceId = hello(httpContext, authenticationContext.getDefaultResourceId()); sessionResourceId = hello(httpContext, sessionResourceId); sessionResourceId = hello(httpContext, sessionResourceId); logoutPost(httpContext);/* w ww . j a v a 2 s . com*/ sessionResourceId = hello(httpContext, authenticationContext.getDefaultResourceId()); sessionResourceId = hello(httpContext, sessionResourceId); hello(httpContext, sessionResourceId); logoutGet(httpContext); hello(httpContext, authenticationContext.getDefaultResourceId()); }
From source file:com.hp.mqm.clt.RestClient.java
protected CloseableHttpResponse execute(HttpUriRequest request) throws IOException { //doFirstLogin(); if (LWSSO_TOKEN == null) { login();//ww w . j a v a 2s . c o m } HttpContext localContext = new BasicHttpContext(); CookieStore localCookies = new BasicCookieStore(); localCookies.addCookie(LWSSO_TOKEN); localContext.setAttribute(HttpClientContext.COOKIE_STORE, localCookies); addClientTypeHeader(request); CloseableHttpResponse response = httpClient.execute(request, localContext); if (isLoginNecessary(response)) { // if request fails with 401 do login and execute request again HttpClientUtils.closeQuietly(response); login(); localCookies.clear(); localCookies.addCookie(LWSSO_TOKEN); localContext.setAttribute(HttpClientContext.COOKIE_STORE, localCookies); response = httpClient.execute(request, localContext); } return response; }