List of usage examples for org.apache.http.impl.client BasicCookieStore BasicCookieStore
public BasicCookieStore()
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?/*ww w. ja v 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:microsoft.exchange.webservices.data.HttpClientWebRequest.java
/** * Method for setting the cookie values. *//*from w w w. j av a 2 s .c o m*/ public void setUserCookie(List<Cookie> rcookies) { if (rcookies != null && rcookies.size() > 0) { if (this.cookieStore == null) { this.cookieStore = new BasicCookieStore(); } for (Cookie c : rcookies) { this.cookieStore.addCookie(c); } } }
From source file:edu.mit.scratch.ScratchProject.java
public void setFavorited(final ScratchSession session, final boolean favorited) throws ScratchProjectException { final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build(); final CookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en"); final BasicClientCookie sessid = new BasicClientCookie("scratchsessionsid", session.getSessionID()); final BasicClientCookie token = new BasicClientCookie("scratchcsrftoken", session.getCSRFToken()); final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true"); lang.setDomain(".scratch.mit.edu"); lang.setPath("/"); sessid.setDomain(".scratch.mit.edu"); sessid.setPath("/"); token.setDomain(".scratch.mit.edu"); token.setPath("/"); debug.setDomain(".scratch.mit.edu"); debug.setPath("/"); cookieStore.addCookie(lang);//www . j a va 2 s . c o m cookieStore.addCookie(sessid); cookieStore.addCookie(token); cookieStore.addCookie(debug); final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig) .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build(); CloseableHttpResponse resp; final HttpUriRequest update = RequestBuilder.put() .setUri("https://scratch.mit.edu/site-api/users/favoriters/" + this.getProjectID() + "/" + (favorited ? "add" : "remove") + "/?usernames=" + session.getUsername()) .addHeader("Accept", "application/json, text/javascript, */*; q=0.01").addHeader("DNT", "1") .addHeader("Referer", "https://scratch.mit.edu/projects/" + this.getProjectID() + "/") .addHeader("Origin", "https://scratch.mit.edu/").addHeader("Accept-Encoding", "gzip, deflate, sdch") .addHeader("Accept-Language", "en-US,en;q=0.8").addHeader("Content-Type", "application/json") .addHeader("X-Requested-With", "XMLHttpRequest").addHeader("Cookie", "scratchsessionsid=" + session.getSessionID() + "; scratchcsrftoken=" + session.getCSRFToken()) .addHeader("X-CSRFToken", session.getCSRFToken()).build(); try { resp = httpClient.execute(update); if (resp.getStatusLine().getStatusCode() != 200) throw new ScratchProjectException(); final BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent())); final StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) result.append(line); } catch (final IOException e) { e.printStackTrace(); throw new ScratchProjectException(); } }
From source file:edu.mit.scratch.ScratchUser.java
public int getMessageCount() throws ScratchUserException { try {/*from ww w . j a v a2s . c o m*/ final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build(); final CookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en"); final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true"); debug.setDomain(".scratch.mit.edu"); debug.setPath("/"); lang.setPath("/"); lang.setDomain(".scratch.mit.edu"); cookieStore.addCookie(lang); cookieStore.addCookie(debug); final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig) .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build(); CloseableHttpResponse resp; final HttpUriRequest update = RequestBuilder.get() .setUri("https://api.scratch.mit.edu/users/" + this.getUsername() + "/messages/count") .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8") .addHeader("Referer", "https://scratch.mit.edu/users/" + this.getUsername() + "/") .addHeader("Origin", "https://scratch.mit.edu") .addHeader("Accept-Encoding", "gzip, deflate, sdch") .addHeader("Accept-Language", "en-US,en;q=0.8").addHeader("Content-Type", "application/json") .addHeader("X-Requested-With", "XMLHttpRequest").build(); try { resp = httpClient.execute(update); } catch (final IOException e) { e.printStackTrace(); throw new ScratchUserException(); } BufferedReader rd; try { rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent())); } catch (UnsupportedOperationException | IOException e) { e.printStackTrace(); throw new ScratchUserException(); } final StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) result.append(line); final JSONObject jsonOBJ2 = new JSONObject(result.toString().trim()); return jsonOBJ2.getInt("count"); } catch (final UnsupportedEncodingException e) { e.printStackTrace(); throw new ScratchUserException(); } catch (final Exception e) { e.printStackTrace(); throw new ScratchUserException(); } }
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;//w w w. j a va 2s .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: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 ava 2 s .c o m*/ httpClient.close(); return result; }
From source file:org.coronastreet.gpxconverter.GarminForm.java
public void upload() { httpClient = HttpClientBuilder.create().build(); localContext = new BasicHttpContext(); cookieStore = new BasicCookieStore(); localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); //httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); if (doLogin()) { try {/*from ww w . j a v a 2 s . co m*/ HttpGet get = new HttpGet("http://connect.garmin.com/transfer/upload#"); HttpResponse formResponse = httpClient.execute(get, localContext); HttpEntity formEntity = formResponse.getEntity(); EntityUtils.consume(formEntity); HttpPost request = new HttpPost( "http://connect.garmin.com/proxy/upload-service-1.1/json/upload/.tcx"); request.setHeader("Referer", "http://connect.garmin.com/api/upload/widget/manualUpload.faces?uploadServiceVersion=1.1"); request.setHeader("Accept", "text/html, application/xhtml+xml, */*"); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("data", new InputStreamBody(document2InputStream(outDoc), "application/octet-stream", "temp.tcx")); // Need to do this bit because without it you can't disable chunked encoding ByteArrayOutputStream bArrOS = new ByteArrayOutputStream(); entity.writeTo(bArrOS); bArrOS.flush(); ByteArrayEntity bArrEntity = new ByteArrayEntity(bArrOS.toByteArray()); bArrOS.close(); bArrEntity.setChunked(false); bArrEntity.setContentEncoding(entity.getContentEncoding()); bArrEntity.setContentType(entity.getContentType()); request.setEntity(bArrEntity); HttpResponse response = httpClient.execute(request, localContext); if (response.getStatusLine().getStatusCode() != 200) { log("Failed to Upload"); HttpEntity en = response.getEntity(); if (en != null) { String output = EntityUtils.toString(en); log(output); } } else { HttpEntity ent = response.getEntity(); if (ent != null) { String output = EntityUtils.toString(ent); output = "[" + output + "]"; //OMG Garmin Sucks at JSON..... JSONObject uploadResponse = new JSONArray(output).getJSONObject(0); JSONObject importResult = uploadResponse.getJSONObject("detailedImportResult"); try { int uploadID = importResult.getInt("uploadId"); log("Success! UploadID is " + uploadID); } catch (Exception e) { JSONArray failures = (JSONArray) importResult.get("failures"); JSONObject failure = (JSONObject) failures.get(0); JSONArray errorMessages = failure.getJSONArray("messages"); JSONObject errorMessage = errorMessages.getJSONObject(0); String content = errorMessage.getString("content"); log("Upload Failed! Error: " + content); } } } httpClient.close(); } catch (Exception ex) { log("Exception? " + ex.getMessage()); ex.printStackTrace(); // handle exception here } } else { log("Failed to upload!"); } }
From source file:org.orbeon.oxf.resources.handler.HTTPURLConnection.java
public void connect() throws IOException { if (!connected) { final String userInfo = url.getUserInfo(); final boolean isAuthenticationRequestedWithUsername = username != null && !username.equals(""); // Create the HTTP client and HTTP context for the client (we expect this to be fairly lightweight) final DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, httpParams); final HttpContext httpContext = new BasicHttpContext(); // Set cookie store, creating a new one if none was provided to us if (cookieStore == null) cookieStore = new BasicCookieStore(); httpClient.setCookieStore(cookieStore); // Set proxy and host authentication if (proxyAuthState != null) httpContext.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState); if (userInfo != null || isAuthenticationRequestedWithUsername) { // Make authentication preemptive; interceptor is added first, as the Authentication header is added // by HttpClient's RequestTargetAuthentication which is itself an interceptor, so our interceptor // needs to run before RequestTargetAuthentication, otherwise RequestTargetAuthentication won't find // the appropriate AuthState/AuthScheme/Credentials in the HttpContext // Don't add the interceptor if we don't want preemptive authentication! if (!"false".equals(preemptiveAuthentication)) { httpClient.addRequestInterceptor(preemptiveAuthHttpRequestInterceptor, 0); }/*w ww .j a v a2s. c o m*/ CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); httpContext.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider); final AuthScope authScope = new AuthScope(url.getHost(), url.getPort()); final Credentials credentials; if (userInfo != null) { // Set username and optional password specified on URL final int separatorPosition = userInfo.indexOf(":"); String username = separatorPosition == -1 ? userInfo : userInfo.substring(0, separatorPosition); String password = separatorPosition == -1 ? "" : userInfo.substring(separatorPosition + 1); // If the username/password contain special character, those character will be encoded, since we // are getting this from a URL. Now do the decoding. username = URLDecoder.decode(username, "utf-8"); password = URLDecoder.decode(password, "utf-8"); credentials = new UsernamePasswordCredentials(username, password); } else { // Set username and password specified externally credentials = domain == null ? new UsernamePasswordCredentials(username, password == null ? "" : password) : new NTCredentials(username, password, url.getHost(), domain); } credentialsProvider.setCredentials(authScope, credentials); } // If method has not been set, use GET // This can happen e.g. when this connection handler is used from URLFactory if (method == null) setRequestMethod("GET"); // Set all headers, final boolean skipAuthorizationHeader = userInfo != null || username != null; for (final Map.Entry<String, String[]> currentEntry : requestProperties.entrySet()) { final String currentHeaderName = currentEntry.getKey(); final String[] currentHeaderValues = currentEntry.getValue(); for (final String currentHeaderValue : currentHeaderValues) { // Skip over Authorization header if user authentication specified if (skipAuthorizationHeader && currentHeaderName.toLowerCase() .equals(Connection.AUTHORIZATION_HEADER.toLowerCase())) continue; method.addHeader(currentHeaderName, currentHeaderValue); } } // Create request entity with body if (method instanceof HttpEntityEnclosingRequest) { // Use the body that was set directly, or the result of writing to the OutputStream final byte[] body = (requestBody != null) ? requestBody : (os != null) ? os.toByteArray() : null; if (body != null) { final Header contentTypeHeader = method.getFirstHeader("Content-Type"); // Header names are case-insensitive for comparison if (contentTypeHeader == null) throw new ProtocolException("Can't set request entity: Content-Type header is missing"); final ByteArrayEntity byteArrayEntity = new ByteArrayEntity(body); byteArrayEntity.setContentType(contentTypeHeader); ((HttpEntityEnclosingRequest) method).setEntity(byteArrayEntity); } } // Make request httpResponse = httpClient.execute(method, httpContext); connected = true; } }
From source file:org.vietspider.net.client.impl.AnonymousHttpClient.java
@Override protected CookieStore createCookieStore() { return new BasicCookieStore(); }
From source file:com.sun.jersey.client.apache4.ApacheHttpClient4.java
/** * Create a default Apache HTTP client handler. * * @param cc ClientConfig instance. Might be null. * * @return a default Apache HTTP client handler. *///from www.ja v a2s . c o m private static ApacheHttpClient4Handler createDefaultClientHandler(final ClientConfig cc) { Object connectionManager = null; Object httpParams = null; if (cc != null) { connectionManager = cc.getProperties().get(ApacheHttpClient4Config.PROPERTY_CONNECTION_MANAGER); if (connectionManager != null) { if (!(connectionManager instanceof ClientConnectionManager)) { Logger.getLogger(ApacheHttpClient4.class.getName()).log(Level.WARNING, "Ignoring value of property " + ApacheHttpClient4Config.PROPERTY_CONNECTION_MANAGER + " (" + connectionManager.getClass().getName() + ") - not instance of org.apache.http.conn.ClientConnectionManager."); connectionManager = null; } } httpParams = cc.getProperties().get(ApacheHttpClient4Config.PROPERTY_HTTP_PARAMS); if (httpParams != null) { if (!(httpParams instanceof HttpParams)) { Logger.getLogger(ApacheHttpClient4.class.getName()).log(Level.WARNING, "Ignoring value of property " + ApacheHttpClient4Config.PROPERTY_HTTP_PARAMS + " (" + httpParams.getClass().getName() + ") - not instance of org.apache.http.params.HttpParams."); httpParams = null; } } } final DefaultHttpClient client = new DefaultHttpClient((ClientConnectionManager) connectionManager, (HttpParams) httpParams); CookieStore cookieStore = null; boolean preemptiveBasicAuth = false; if (cc != null) { for (Map.Entry<String, Object> entry : cc.getProperties().entrySet()) client.getParams().setParameter(entry.getKey(), entry.getValue()); if (cc.getPropertyAsFeature(ApacheHttpClient4Config.PROPERTY_DISABLE_COOKIES)) client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES); Object credentialsProvider = cc.getProperty(ApacheHttpClient4Config.PROPERTY_CREDENTIALS_PROVIDER); if (credentialsProvider != null && (credentialsProvider instanceof CredentialsProvider)) { client.setCredentialsProvider((CredentialsProvider) credentialsProvider); } final Object proxyUri = cc.getProperties().get(ApacheHttpClient4Config.PROPERTY_PROXY_URI); if (proxyUri != null) { final URI u = getProxyUri(proxyUri); final HttpHost proxy = new HttpHost(u.getHost(), u.getPort(), u.getScheme()); if (cc.getProperties().containsKey(ApacheHttpClient4Config.PROPERTY_PROXY_USERNAME) && cc.getProperties().containsKey(ApacheHttpClient4Config.PROPERTY_PROXY_PASSWORD)) { client.getCredentialsProvider().setCredentials(new AuthScope(u.getHost(), u.getPort()), new UsernamePasswordCredentials( cc.getProperty(ApacheHttpClient4Config.PROPERTY_PROXY_USERNAME).toString(), cc.getProperty(ApacheHttpClient4Config.PROPERTY_PROXY_PASSWORD).toString())); } client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } preemptiveBasicAuth = cc .getPropertyAsFeature(ApacheHttpClient4Config.PROPERTY_PREEMPTIVE_BASIC_AUTHENTICATION); } if (client.getParams().getParameter(ClientPNames.COOKIE_POLICY) == null || !client.getParams() .getParameter(ClientPNames.COOKIE_POLICY).equals(CookiePolicy.IGNORE_COOKIES)) { cookieStore = new BasicCookieStore(); client.setCookieStore(cookieStore); } return new ApacheHttpClient4Handler(client, cookieStore, preemptiveBasicAuth); }