List of usage examples for org.apache.http.impl.client DefaultHttpClient getConnectionManager
public synchronized final ClientConnectionManager getConnectionManager()
From source file:org.bibalex.gallery.storage.BAGStorage.java
public static List<String> listChildren(String dirUrlStr, FileType childrenType, int timeout) throws BAGException { try {/* w w w . j a v a 2s.c o m*/ List<String> result; if (new URI(dirUrlStr).getScheme().startsWith("http")) { BasicHttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, timeout); DefaultHttpClient httpClient = new DefaultHttpClient(httpParams); try { result = listChildrenApacheHttpd(dirUrlStr, childrenType, httpClient); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpClient.getConnectionManager().shutdown(); } } else { result = new ArrayList<String>(); FileSystemManager fsMgr = VFS.getManager(); FileObject dir = fsMgr.resolveFile(dirUrlStr); final FileObject[] children = dir.getChildren(); for (final FileObject child : children) { if ((childrenType == FileType.FILE_OR_FOLDER) || (child.getType() == childrenType)) { result.add(child.getName().getBaseName()); } } } // TODO define a comparator that orders the files properly as in // http://forums.sun.com/thread.jspa?threadID=5289401 Collections.sort(result); return result; } catch (FileSystemException e) { throw new BAGException(e); } catch (URISyntaxException e) { throw new BAGException(e); } }
From source file:com.senseidb.dataprovider.http.HttpsClientDecorator.java
public static DefaultHttpClient decorate(DefaultHttpClient base) { try {//from w w w . j ava 2 s.c om SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = base.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", 443, ssf)); return new DefaultHttpClient(ccm, base.getParams()); } catch (Exception ex) { logger.error(ex.getMessage(), ex); return null; } }
From source file:org.androidnerds.reader.util.api.Authentication.java
/** * This method generates a quick token to send with API requests that require * editing content. This method is called as the API request is being built so * that it doesn't expire prior to the actual execution. * * @param sid - the user's authentication token from ClientLogin * @return token - the edit token generated by the server. * *//* w w w . j av a 2 s . co m*/ public static String generateFastToken(String sid) { try { BasicClientCookie cookie = Authentication.buildCookie(sid); DefaultHttpClient client = new DefaultHttpClient(); client.getCookieStore().addCookie(cookie); HttpGet get = new HttpGet(TOKEN_URL); HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); Log.d(TAG, "Server Response: " + response.getStatusLine()); InputStream in = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = null; while ((line = reader.readLine()) != null) { Log.d(TAG, "Response Content: " + line); } reader.close(); client.getConnectionManager().shutdown(); return line; } catch (Exception e) { Log.d(TAG, "Exception caught:: " + e.toString()); return null; } }
From source file:org.jboss.tools.feedhenry.ui.model.HttpUtil.java
/** * Set the proxy settings from ProxyService. * This method sets a {@link HttpRoutePlanner} to the client * /*ww w .jav a 2s. c o m*/ * @param client */ static void setupProxy(final DefaultHttpClient client) { client.setRoutePlanner(new HttpRoutePlanner() { /* (non-Javadoc) * @see org.apache.http.conn.routing.HttpRoutePlanner#determineRoute(org.apache.http.HttpHost, org.apache.http.HttpRequest, org.apache.http.protocol.HttpContext) */ @Override public HttpRoute determineRoute(HttpHost target, HttpRequest request, HttpContext context) throws HttpException { //use forced route if one exists HttpRoute route = ConnRouteParams.getForcedRoute(request.getParams()); if (route != null) return route; // if layered, is it secure? final Scheme scheme = client.getConnectionManager().getSchemeRegistry().getScheme(target); final boolean secure = scheme.isLayered(); final IProxyService proxy = FHPlugin.getDefault().getProxyService(); HttpHost host = null; if (proxy != null) { try { IProxyData[] proxyDatas = proxy.select(new URI(target.toURI())); for (IProxyData data : proxyDatas) { if (data.getType().equals(IProxyData.HTTP_PROXY_TYPE)) { host = new HttpHost(data.getHost(), data.getPort()); break; } } } catch (URISyntaxException e) { FHPlugin.log(IStatus.ERROR, "Incorrect URI", e); } } if (host == null) { return new HttpRoute(target, null, secure); } return new HttpRoute(target, null, host, secure); } }); }
From source file:costumetrade.common.util.HttpClientUtils.java
public static String get(String url, String encoding) throws ClientProtocolException, IOException { DefaultHttpClient httpclient = new DefaultHttpClient(); try {/*from www . j a v a 2 s . c om*/ httpclient.getParams().setBooleanParameter(CookieSpecPNames.SINGLE_COOKIE_HEADER, true); //log.info("GET "+url); HttpGet httpget = new HttpGet(url); httpget.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)"); HttpResponse response = httpclient.execute(httpget); //log.info(response.getStatusLine().getStatusCode()); HttpEntity entity = response.getEntity(); return EntityUtils.toString(entity, encoding); } finally { if (httpclient != null) { httpclient.getConnectionManager().shutdown(); } } }
From source file:com.bourke.kitchentimer.utils.Utils.java
public static void notifyServer(final String serverUrl) { new Thread(new Runnable() { @Override//w ww . j a va 2s . c om public void run() { try { Log.d("Utils", "notifyServer:" + serverUrl); DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(serverUrl); URL url = new URL(serverUrl); String userInfo = url.getUserInfo(); if (userInfo != null) { httpget.addHeader("Authorization", "Basic " + Base64.encodeToString(userInfo.getBytes(), Base64.NO_WRAP)); } HttpResponse response = httpclient.execute(httpget); response.getEntity().getContent().close(); httpclient.getConnectionManager().shutdown(); int status = response.getStatusLine().getStatusCode(); if (status < 200 || status > 299) { throw new Exception(response.getStatusLine().toString()); } } catch (Exception ex) { Log.e("Utils", "Error notifying server: ", ex); } } }).start(); }
From source file:com.quietlycoding.android.reader.util.api.Authentication.java
/** * This method generates a quick token to send with API requests that * require editing content. This method is called as the API request is * being built so that it doesn't expire prior to the actual execution. * //from w w w . j a v a2 s . com * @param sid * - the user's authentication token from ClientLogin * @return token - the edit token generated by the server. * */ public static String generateFastToken(String sid) { try { final BasicClientCookie cookie = Authentication.buildCookie(sid); final DefaultHttpClient client = new DefaultHttpClient(); client.getCookieStore().addCookie(cookie); final HttpGet get = new HttpGet(TOKEN_URL); final HttpResponse response = client.execute(get); final HttpEntity entity = response.getEntity(); Log.d(TAG, "Server Response: " + response.getStatusLine()); final InputStream in = entity.getContent(); final BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = null; while ((line = reader.readLine()) != null) { Log.d(TAG, "Response Content: " + line); } reader.close(); client.getConnectionManager().shutdown(); return line; } catch (final Exception e) { Log.d(TAG, "Exception caught:: " + e.toString()); return null; } }
From source file:com.mycompany.trader.HTTPTransport.java
public static String sendData(HttpPost data, String header) throws Exception { try {// w w w. j a v a 2s . com DefaultHttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(data); StringBuilder buffer = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output; while ((output = br.readLine()) != null) { buffer.append(output); } System.out.println("response from server:"); System.out.println(buffer.toString()); if (response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 201) { buffer.append("error_code:" + response.getStatusLine().getStatusCode()); } httpClient.getConnectionManager().shutdown(); return buffer.toString(); } catch (Exception e) { //e.printStackTrace(); throw new Exception("server returned code: " + e.getMessage()); } }
From source file:org.apiwatch.util.IO.java
public static void putAPIData(APIScope scope, String format, String encoding, String location, String username, String password) throws SerializationError, IOException, HttpException { if (URL_RX.matcher(location).matches()) { DefaultHttpClient client = new DefaultHttpClient(); if (username != null && password != null) { client.getCredentialsProvider().setCredentials(new AuthScope(null, -1), new UsernamePasswordCredentials(username, password)); }/*ww w . j a v a2 s . c om*/ HttpPost req = new HttpPost(location); StringWriter writer = new StringWriter(); Serializers.dumpAPIScope(scope, writer, format); HttpEntity entity = new StringEntity(writer.toString(), encoding); req.setEntity(entity); req.setHeader("content-type", format); req.setHeader("content-encoding", encoding); HttpResponse response = client.execute(req); client.getConnectionManager().shutdown(); if (response.getStatusLine().getStatusCode() >= 400) { throw new HttpException(response.getStatusLine().getReasonPhrase()); } LOGGER.info("Sent results to URL: " + location); } else { File dir = new File(location); dir.mkdirs(); File file = new File(dir, "api." + format); OutputStream out = new FileOutputStream(file); Writer writer = new OutputStreamWriter(out, encoding); Serializers.dumpAPIScope(scope, writer, format); writer.flush(); writer.close(); out.close(); LOGGER.info("Wrote results to file: " + file); } }
From source file:com.mycompany.trader.HTTPTransport.java
public static String sendGetReq(HttpGet data) { try {/*from w w w.j a v a2 s. c o m*/ DefaultHttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(data); StringBuilder buffer = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output; while ((output = br.readLine()) != null) { buffer.append(output); } System.out.println("response from server:"); System.out.println(buffer.toString()); if (response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 201) { throw new Exception("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } httpClient.getConnectionManager().shutdown(); return buffer.toString(); } catch (Exception e) { return null; } }