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:net.vexelon.mobileops.GLBClient.java
/** * Initialize Http Client/* ww w . ja v a2 s . c o m*/ */ private void initHttpClient() { HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); params.setParameter(CoreProtocolPNames.USER_AGENT, UserAgentHelper.getRandomUserAgent()); //params.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, HTTP.UTF_8); // Bugfix #1: The target server failed to respond params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE); DefaultHttpClient client = new DefaultHttpClient(params); httpCookieStore = new BasicCookieStore(); client.setCookieStore(httpCookieStore); httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.COOKIE_STORE, httpCookieStore); // Bugfix #1: Adding retry handler to repeat failed requests HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= MAX_REQUEST_RETRIES) { return false; } if (exception instanceof NoHttpResponseException || exception instanceof ClientProtocolException) { return true; } return false; } }; client.setHttpRequestRetryHandler(retryHandler); // SSL HostnameVerifier verifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; try { SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", new PlainSocketFactory(), 80)); registry.register(new Scheme("https", new TrustAllSocketFactory(), 443)); SingleClientConnManager connMgr = new SingleClientConnManager(client.getParams(), registry); httpClient = new DefaultHttpClient(connMgr, client.getParams()); } catch (InvalidAlgorithmParameterException e) { // Log.e(Defs.LOG_TAG, "", e); // init without connection manager httpClient = new DefaultHttpClient(client.getParams()); } HttpsURLConnection.setDefaultHostnameVerifier(verifier); }
From source file:org.auraframework.integration.test.util.AuraHttpTestCase.java
/** * Creates HttpContext with httpclient cookie store. Allows cookies to be part of specific request method. * * @return http context/*from w w w . j a v a2 s .c o m*/ * @throws Exception */ protected HttpContext getHttpCookieContext() throws Exception { CookieStore cookieStore = getCookieStore(); HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); return localContext; }
From source file:gtu.youtube.JavaYoutubeDownloader.java
private void play(String videoId, int format, String encoding, String userAgent, File outputdir, String extension) throws Throwable { // ?Youtube?//from w w w .j av a 2 s . c o m JavaYoutubeVideoUrlHandler urlHandler = new JavaYoutubeVideoUrlHandler(videoId, String.valueOf(format), userAgent); // ? log.fine("Retrieving " + videoId); List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("video_id", videoId)); qparams.add(new BasicNameValuePair("fmt", "" + format)); URI uri = getUri("get_video_info", qparams); CookieStore cookieStore = new BasicCookieStore(); if (true) { InputStream is = this.getClass().getResource("JavaYoutubeDownloader_cookies.txt").openStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); String cookieContent = baos.toString("UTF-8"); cookieStore = this.getCookieString(cookieContent); } HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(uri); if (userAgent != null && userAgent.length() > 0) { httpget.setHeader("User-Agent", userAgent); } log.finer("Executing " + uri); HttpResponse response = httpclient.execute(httpget, localContext); HttpEntity entity = response.getEntity(); if (entity != null && response.getStatusLine().getStatusCode() == 200) { InputStream instream = entity.getContent(); String videoInfo = getStringFromInputStream(encoding, instream); System.out.println("videoInfo = " + videoInfo); if (videoInfo != null && videoInfo.length() > 0) { List<NameValuePair> infoMap = new ArrayList<NameValuePair>(); URLEncodedUtils.parse(infoMap, new Scanner(videoInfo), encoding); System.out.println("infoMap = " + infoMap); String downloadUrl = null; String filename = videoId; for (NameValuePair pair : infoMap) { String key = pair.getName(); String val = pair.getValue(); log.finest(key + "=" + val); // System.out.println(key + "\t" + val); if (key.equals("title")) { filename = val; } else if (key.equals("fmt_url_map")) { // String[] formats = commaPattern.split(val); boolean found = false; for (String fmt : formats) { String[] fmtPieces = pipePattern.split(fmt); if (fmtPieces.length == 2) { int pieceFormat = Integer.parseInt(fmtPieces[0]); log.fine("Available format=" + pieceFormat); if (pieceFormat == format) { // found what we want downloadUrl = fmtPieces[1]; System.out.println(">>> downloadUrl = " + downloadUrl); found = true; break; } } } if (!found) { log.warning( "Could not find video matching specified format, however some formats of the video do exist (use -verbose)."); } } } filename = cleanFilename(filename); if (filename.length() == 0) { filename = videoId; } else { filename += "_" + videoId; } filename += "." + extension; File outputfile = new File(outputdir, filename); // ?1 if (downloadUrl == null) { downloadUrl = customDownloadUrl_by_gtu001; } // ?2 if (downloadUrl == null) { JavaYoutubeVideoUrlHandler gtu001 = new JavaYoutubeVideoUrlHandler(videoId, "", userAgent); downloadUrl = gtu001.getUrl(format); } if (downloadUrl != null) { downloadWithHttpClient(userAgent, downloadUrl, outputfile); } else { log.severe("Could not find video"); } } else { log.severe("Did not receive content from youtube"); } } else { log.severe("Could not contact youtube: " + response.getStatusLine()); } }
From source file:de.stkl.gbgvertretungsplan.sync.SyncAdapter.java
public static boolean tryLogin(String username, String password) throws CommunicationInterface.ParsingException, IOException, CommunicationInterface.CommunicationException { AndroidHttpClient httpClient = AndroidHttpClient.newInstance(null); CookieStore cookies = new BasicCookieStore(); HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookies); boolean result = tryLogin(httpClient, localContext, username, password); // cleanup/* w ww . j a v a2 s . c o m*/ httpClient.close(); return result; }
From source file:self.philbrown.javaQuery.AjaxTask.java
@Override protected TaskResponse doInBackground(Void... arg0) { //handle cached responses CachedResponse cachedResponse = URLresponses .get(String.format(Locale.US, "%s_?=%s", options.url(), options.dataType())); //handle ajax caching option if (cachedResponse != null) { if (options.cache()) { if (new Date().getTime() - cachedResponse.timestamp.getTime() < options.cacheTimeout()) { //return cached response Success s = new Success(); s.obj = cachedResponse.response; s.reason = "cached response"; s.headers = null;//from w ww . ja v a 2 s. c o m return s; } } } if (request == null) { String type = options.type(); if (type == null) type = "GET"; if (type.equalsIgnoreCase("DELETE")) { request = new HttpDelete(options.url()); } else if (type.equalsIgnoreCase("GET")) { request = new HttpGet(options.url()); } else if (type.equalsIgnoreCase("HEAD")) { request = new HttpHead(options.url()); } else if (type.equalsIgnoreCase("OPTIONS")) { request = new HttpOptions(options.url()); } else if (type.equalsIgnoreCase("POST")) { request = new HttpPost(options.url()); } else if (type.equalsIgnoreCase("PUT")) { request = new HttpPut(options.url()); } else if (type.equalsIgnoreCase("TRACE")) { request = new HttpTrace(options.url()); } else if (type.equalsIgnoreCase("CUSTOM")) { try { request = options.customRequest(); } catch (Exception e) { request = null; } if (request == null) { Log.w("javaQuery.ajax", "CUSTOM type set, but AjaxOptions.customRequest is invalid. Defaulting to GET."); request = new HttpGet(); } } else { //default to GET request = new HttpGet(); } } Map<String, Object> args = new HashMap<String, Object>(); args.put("options", options); args.put("request", request); EventCenter.trigger("ajaxPrefilter", args, null); if (options.headers() != null) { if (options.headers().authorization() != null) { options.headers() .authorization(options.headers().authorization() + " " + options.getEncodedCredentials()); } else if (options.username() != null) { //guessing that authentication is basic options.headers().authorization("Basic " + options.getEncodedCredentials()); } for (Entry<String, String> entry : options.headers().map().entrySet()) { request.addHeader(entry.getKey(), entry.getValue()); } } if (options.data() != null) { try { Method setEntity = request.getClass().getMethod("setEntity", new Class<?>[] { HttpEntity.class }); if (options.processData() == null) { setEntity.invoke(request, new StringEntity(options.data().toString())); } else { Class<?> dataProcessor = Class.forName(options.processData()); Constructor<?> constructor = dataProcessor.getConstructor(new Class<?>[] { Object.class }); setEntity.invoke(request, constructor.newInstance(options.data())); } } catch (Throwable t) { Log.w("Ajax", "Could not post data"); } } HttpParams params = new BasicHttpParams(); if (options.timeout() != 0) { HttpConnectionParams.setConnectionTimeout(params, options.timeout()); HttpConnectionParams.setSoTimeout(params, options.timeout()); } HttpClient client = new DefaultHttpClient(params); HttpResponse response = null; try { if (options.cookies() != null) { CookieStore cookies = new BasicCookieStore(); for (Entry<String, String> entry : options.cookies().entrySet()) { cookies.addCookie(new BasicClientCookie(entry.getKey(), entry.getValue())); } HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookies); response = client.execute(request, httpContext); } else { response = client.execute(request); } if (options.dataFilter() != null) { if (options.context() != null) options.dataFilter().invoke(new $(options.context()), response, options.dataType()); else options.dataFilter().invoke(null, response, options.dataType()); } StatusLine statusLine = response.getStatusLine(); Function function = options.statusCode().get(statusLine); if (function != null) { if (options.context() != null) function.invoke(new $(options.context())); else function.invoke(null); } if (statusLine.getStatusCode() >= 300) { //an error occurred Error e = new Error(); AjaxError error = new AjaxError(); error.request = request; error.options = options; e.status = statusLine.getStatusCode(); e.reason = statusLine.getReasonPhrase(); error.status = e.status; error.reason = e.reason; e.headers = response.getAllHeaders(); e.error = error; return e; } else { //handle dataType String dataType = options.dataType(); if (dataType == null) dataType = "text"; Object parsedResponse = null; boolean success = true; try { if (dataType.equalsIgnoreCase("text") || dataType.equalsIgnoreCase("html")) { parsedResponse = parseText(response); } else if (dataType.equalsIgnoreCase("xml")) { if (options.customXMLParser() != null) { InputStream is = response.getEntity().getContent(); if (options.SAXContentHandler() != null) options.customXMLParser().parse(is, options.SAXContentHandler()); else options.customXMLParser().parse(is, new DefaultHandler()); parsedResponse = "Response handled by custom SAX parser"; } else if (options.SAXContentHandler() != null) { InputStream is = response.getEntity().getContent(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/namespaces", false); factory.setFeature("http://xml.org/sax/features/namespace-prefixes", true); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setContentHandler(options.SAXContentHandler()); reader.parse(new InputSource(is)); parsedResponse = "Response handled by custom SAX content handler"; } else { parsedResponse = parseXML(response); } } else if (dataType.equalsIgnoreCase("json")) { parsedResponse = parseJSON(response); } else if (dataType.equalsIgnoreCase("script")) { parsedResponse = parseScript(response); } else if (dataType.equalsIgnoreCase("image")) { parsedResponse = parseImage(response); } } catch (ClientProtocolException cpe) { if (options.debug()) cpe.printStackTrace(); success = false; Error e = new Error(); AjaxError error = new AjaxError(); error.request = request; error.options = options; e.status = statusLine.getStatusCode(); e.reason = statusLine.getReasonPhrase(); error.status = e.status; error.reason = e.reason; e.headers = response.getAllHeaders(); e.error = error; return e; } catch (Exception ioe) { if (options.debug()) ioe.printStackTrace(); success = false; Error e = new Error(); AjaxError error = new AjaxError(); error.request = request; error.options = options; e.status = statusLine.getStatusCode(); e.reason = statusLine.getReasonPhrase(); error.status = e.status; error.reason = e.reason; e.headers = response.getAllHeaders(); e.error = error; return e; } if (success) { //Handle cases where successful requests still return errors (these include //configurations in AjaxOptions and HTTP Headers String key = String.format(Locale.US, "%s_?=%s", options.url(), options.dataType()); CachedResponse cache = URLresponses.get(key); Date now = new Date(); //handle ajax caching option if (cache != null) { if (options.cache()) { if (now.getTime() - cache.timestamp.getTime() < options.cacheTimeout()) { parsedResponse = cache; } else { cache.response = parsedResponse; cache.timestamp = now; synchronized (URLresponses) { URLresponses.put(key, cache); } } } } //handle ajax ifModified option Header[] lastModifiedHeaders = response.getHeaders("last-modified"); if (lastModifiedHeaders.length >= 1) { try { Header h = lastModifiedHeaders[0]; SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz"); Date lastModified = format.parse(h.getValue()); if (options.ifModified() && lastModified != null) { if (cache.lastModified != null && cache.lastModified.compareTo(lastModified) == 0) { //request response has not been modified. //Causes an error instead of a success. Error e = new Error(); AjaxError error = new AjaxError(); error.request = request; error.options = options; e.status = statusLine.getStatusCode(); e.reason = statusLine.getReasonPhrase(); error.status = e.status; error.reason = e.reason; e.headers = response.getAllHeaders(); e.error = error; Function func = options.statusCode().get(304); if (func != null) { if (options.context() != null) func.invoke(new $(options.context())); else func.invoke(null); } return e; } else { cache.lastModified = lastModified; synchronized (URLresponses) { URLresponses.put(key, cache); } } } } catch (Throwable t) { Log.e("Ajax", "Could not parse Last-Modified Header"); } } //Now handle a successful request Success s = new Success(); s.obj = parsedResponse; s.reason = statusLine.getReasonPhrase(); s.headers = response.getAllHeaders(); return s; } //success Success s = new Success(); s.obj = parsedResponse; s.reason = statusLine.getReasonPhrase(); s.headers = response.getAllHeaders(); return s; } } catch (Throwable t) { if (options.debug()) t.printStackTrace(); if (t instanceof java.net.SocketTimeoutException) { Error e = new Error(); AjaxError error = new AjaxError(); error.request = request; error.options = options; e.status = 0; String reason = t.getMessage(); if (reason == null) reason = "Socket Timeout"; e.reason = reason; error.status = e.status; error.reason = e.reason; if (response != null) e.headers = response.getAllHeaders(); else e.headers = new Header[0]; e.error = error; return e; } return null; } }
From source file:org.mobicents.applications.ussd.examples.http.push.HTTPPush.java
protected void establishSession() { this.context = new BasicHttpContext(); CookieStore cookieStore = new BasicCookieStore(); this.context.setAttribute(ClientContext.COOKIE_STORE, cookieStore); }
From source file:ilarkesto.net.ApacheHttpDownloader.java
public HttpContext getContext() { if (context == null) { context = new BasicHttpContext(); context.setAttribute(ClientContext.COOKIE_STORE, new BasicCookieStore()); }/*from w ww . j a v a2 s .co m*/ return context; }
From source file:fr.ippon.wip.http.hc.HttpClientResourceManager.java
/** * Create an HttpContext configured with a CredentialsProvider and a * CookieStore according to the current sessionID/windowID. * /*from w ww . j av a2s .co m*/ * Current PortletRequest, PortletResponse and Request instances are also * associated to the current for future usage (@see * TransformerResponseInterceptor and LtpaRequestInterceptor). * * It is necessary to call #releaseThreadResources in a finally clause when * HTTP processing is done. * * @param portletRequest * @param portletResponse * @param request * @return */ public HttpContext initExecutionContext(PortletRequest portletRequest, PortletResponse portletResponse, RequestBuilder request) { HttpContext context = new BasicHttpContext(); CredentialsProvider credentialsProvider = getCredentialsProvider(portletRequest); context.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider); context.setAttribute(ClientContext.COOKIE_STORE, getCookieStore(portletRequest)); context.setAttribute("WIP_CONFIGURATION", WIPUtil.getConfiguration(portletRequest)); currentPortletRequest.set(portletRequest); currentPortletResponse.set(portletResponse); currentRequest.set(request); return context; }
From source file:org.callimachusproject.client.HttpClientFactoryTest.java
@Test public void testCookieStored() throws Exception { CookieStore cookieStore = new BasicCookieStore(); do {//from w ww . j av a 2s. c o m HttpGet get = new HttpGet("http://example.com/setcookie"); HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); get.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109); BasicHttpResponse setcookie = new BasicHttpResponse(_200); setcookie.addHeader("Set-Cookie", "oat=meal"); setcookie.addHeader("Cache-Control", "no-store"); responses.add(setcookie); client.execute(get, new ResponseHandler<Void>() { public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException { assertEquals(_200.getStatusCode(), response.getStatusLine().getStatusCode()); assertTrue(response.containsHeader("Set-Cookie")); return null; } }, localContext); } while (false); do { HttpGet get = new HttpGet("http://example.com/getcookie"); HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); get.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109); BasicHttpResponse getcookie = new BasicHttpResponse(_200); responses.add(getcookie); client.execute(get, new ResponseHandler<Void>() { public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException { assertEquals(_200.getStatusCode(), response.getStatusLine().getStatusCode()); assertContains("oat=meal", asString(response.getEntity())); return null; } }, localContext); } while (false); }
From source file:net.fizzl.redditengine.impl.SimpleHttpClient.java
/** * Private constructor. To get an instance use {@link #getInstance()} * @see AndroidHttpClient/*from w w w .j a v a2 s . co m*/ */ private SimpleHttpClient() { mClient = AndroidHttpClient.newInstance(USER_AGENT); HttpParams params = mClient.getParams(); HttpClientParams.setRedirecting(params, true); mCookieStore = new PersistentCookieStore(); mHttpContext = new BasicHttpContext(); mHttpContext.setAttribute(ClientContext.COOKIE_STORE, mCookieStore); }