List of usage examples for org.apache.http.impl.client DefaultHttpClient getConnectionManager
public synchronized final ClientConnectionManager getConnectionManager()
From source file:org.peterbaldwin.client.android.delicious.WebPageTitleRequest.java
/** * {@inheritDoc}//from w ww. ja v a 2s .com */ public void run() { try { DefaultHttpClient client = new DefaultHttpClient(); client.setRedirectHandler(this); try { HttpGet request = new HttpGet(mUrl); // Set a generic User-Agent to avoid being // redirected to a mobile UI. request.addHeader("User-Agent", "Mozilla/5.0"); HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); try { int statusCode = statusLine.getStatusCode(); if (statusCode != HttpStatus.SC_OK) { throw new IOException("Unexpected response code: " + statusCode); } // Send redirect before checking content type // because the redirect is important even if the // title cannot be extracted. if (mRedirectLocation != null && !mUrl.equals(mRedirectLocation)) { int what = HANDLE_REDIRECT; Object obj = mRedirectLocation; Message msg = mHandler.obtainMessage(what, obj); msg.sendToTarget(); } Header contentType = entity.getContentType(); if (contentType != null) { String value = contentType.getValue(); if (!isHtml(value)) { // This is important because the user might try // bookmarking a video or another large file. throw new IOException("Unsupported content type: " + value); } } else { throw new IOException("Content type is missing"); } String source = EntityUtils.toString(entity); Html.ImageGetter imageGetter = null; Html.TagHandler tagHandler = this; Html.fromHtml(source, imageGetter, tagHandler); } finally { if (entity != null) { entity.consumeContent(); } } } finally { client.getConnectionManager().shutdown(); } } catch (TerminateParser e) { // Thrown by handleTag to terminate parser early. } catch (IOException e) { Log.e(LOG_TAG, "i/o error", e); } catch (RuntimeException e) { Log.e(LOG_TAG, "runtime error", e); } catch (Error e) { Log.e(LOG_TAG, "severe error", e); } finally { Message msg = mHandler.obtainMessage(HANDLE_TITLE, mTitle); msg.sendToTarget(); } }
From source file:com.adam.aslfms.service.Handshaker.java
/** * Connects to Last.fm servers and tries to handshake/authenticate. A * successful handshake is needed for all other submission requests. If an * error occurs, exceptions are thrown./*www . jav a 2 s . c o m*/ * * @return the result of a successful handshake, {@link HandshakeResult} * @throws BadAuthException * means that the username/password provided by the user was * wrong, or that the user requested his/her credentials to be * cleared. * @throws TemporaryFailureException * @throws UnknownResponseException * {@link UnknownResponseException} * @throws ClientBannedException * this version of the client has been banned */ public HandshakeResult handshake() throws BadAuthException, TemporaryFailureException, ClientBannedException { Log.d(TAG, "Handshaking: " + getNetApp().getName()); String username = settings.getUsername(getNetApp()); String pwdMd5 = settings.getPwdMd5(getNetApp()); if (username.length() == 0) { Log.d(TAG, "Invalid (empty) username for: " + getNetApp().getName()); throw new BadAuthException(getContext().getString(R.string.auth_bad_auth)); } // ----------------------------------------------------------------------- // ------------ for debug // ------------------------------------------------ // use these values if you are testing or developing a new app // String clientid = "tst"; // String clientver = "1.0"; // ----------------------------------------------------------------------- // ------------ for this app // --------------------------------------------- // ----------------------------------------------------------------------- // These values should only be used for SLS. If other code // misbehaves using these values, this app might get banned. // You can ask Last.fm for your own ids. String clientid = getContext().getString(R.string.client_id); String clientver = getContext().getString(R.string.client_ver); // ------------ end // ------------------------------------------------------ // ----------------------------------------------------------------------- String time = new Long(Util.currentTimeSecsUTC()).toString(); String authToken = MD5.getHashString(pwdMd5 + time); String uri = getNetApp().getHandshakeUrl() + "&p=1.2.1&c=" + clientid + "&v=" + clientver + "&u=" + enc(username) + "&t=" + time + "&a=" + authToken; DefaultHttpClient http = new DefaultHttpClient(); HttpGet request = new HttpGet(uri); try { ResponseHandler<String> handler = new BasicResponseHandler(); String response = http.execute(request, handler); String[] lines = response.split("\n"); if (lines.length == 4 && lines[0].equals("OK")) { // handshake succeeded Log.i(TAG, "Handshake succeeded!: " + getNetApp().getName()); HandshakeResult hi = new HandshakeResult(lines[1], lines[2], lines[3]); return hi; } else if (lines.length == 1) { if (lines[0].startsWith("BANNED")) { Log.e(TAG, "Handshake fails: client banned: " + getNetApp().getName()); throw new ClientBannedException(getContext().getString(R.string.auth_client_banned)); } else if (lines[0].startsWith("BADAUTH")) { Log.i(TAG, "Handshake fails: bad auth: " + getNetApp().getName()); throw new BadAuthException(getContext().getString(R.string.auth_bad_auth)); } else if (lines[0].startsWith("BADTIME")) { Log.e(TAG, "Handshake fails: bad time: " + getNetApp().getName()); throw new TemporaryFailureException(getContext().getString(R.string.auth_timing_error)); } else if (lines[0].startsWith("FAILED")) { String reason = lines[0].substring(7); Log.e(TAG, "Handshake fails: FAILED " + reason + ": " + getNetApp().getName()); throw new TemporaryFailureException( getContext().getString(R.string.auth_server_error).replace("%1", reason)); } } else { throw new TemporaryFailureException( "Weird response from handskake-req: " + response + ": " + getNetApp().getName()); } } catch (ClientProtocolException e) { throw new TemporaryFailureException(TAG + ": " + e.getMessage()); } catch (IOException e) { throw new TemporaryFailureException(TAG + ": " + e.getMessage()); } finally { http.getConnectionManager().shutdown(); } return null; }
From source file:cn.geowind.takeout.verify.JsonRestApi.java
/** * @brief ??/* w w w . j ava 2 s.co m*/ * @param accountSid * ? * @param authToken * ? * @param appId * id * @param to * ? * @return HttpPost ??? * @throws NoSuchAlgorithmException * @throws KeyManagementException */ public String sendTemplateSMS(String accountSid, String authToken, String appId, String to, String code) throws NoSuchAlgorithmException, KeyManagementException { String result = ""; // HttpClient CcopHttpClient chc = new CcopHttpClient(); DefaultHttpClient httpclient = chc.registerSSL("app.cloopen.com", "TLS", 8883, "https"); try { // URL String timestamp = DateUtil.dateToStr(new Date(), DateUtil.DATE_TIME_NO_SLASH); // md5(Id + ? + ) String sig = accountSid + authToken + timestamp; // MD5 EncryptUtil eu = new EncryptUtil(); String signature = eu.md5Digest(sig); StringBuffer sb = new StringBuffer(); String url = sb.append(SMS_BASE_URL).append(SMS_VERSION).append("/Accounts/").append(accountSid) .append(SMS).append(TEMPLATE_SMS).append("?sig=").append(signature).toString(); // HttpPost HttpPost httppost = new HttpPost(url); setHttpHeader(httppost); String src = accountSid + ":" + timestamp; String auth = eu.base64Encoder(src); httppost.setHeader("Authorization", auth);// base64(Id + ? + // ) JSONObject obj = new JSONObject(); obj.put("to", to); obj.put("appId", appId); obj.put("templateId", SMS_TEMPLATE_ID); JSONArray replace = new JSONArray(); replace.put(code); obj.put("datas", replace); String data = obj.toString(); System.out.println("---------------------------- SendSMS for JSON begin----------------------------"); System.out.println("data: " + data); BasicHttpEntity requestBody = new BasicHttpEntity(); requestBody.setContent(new ByteArrayInputStream(data.getBytes("UTF-8"))); requestBody.setContentLength(data.getBytes("UTF-8").length); httppost.setEntity(requestBody); // HttpResponse response = httpclient.execute(httppost); // ??? HttpEntity entity = response.getEntity(); if (entity != null) { result = EntityUtils.toString(entity, "UTF-8"); } // ?HTTP?? EntityUtils.consume(entity); } catch (Exception e) { e.printStackTrace(); } finally { // httpclient.getConnectionManager().shutdown(); } // ??? return result; }
From source file:org.openmrs.module.dhisconnector.api.impl.DHISConnectorServiceImpl.java
@Override public String getDataFromDHISEndpoint(String endpoint) { String url = Context.getAdministrationService().getGlobalProperty("dhisconnector.url"); String user = Context.getAdministrationService().getGlobalProperty("dhisconnector.user"); String pass = Context.getAdministrationService().getGlobalProperty("dhisconnector.pass"); DefaultHttpClient client = null; String payload = ""; try {// w ww . j ava 2 s . c o m URL dhisURL = new URL(url); String host = dhisURL.getHost(); int port = dhisURL.getPort(); HttpHost targetHost = new HttpHost(host, port, dhisURL.getProtocol()); client = new DefaultHttpClient(); BasicHttpContext localcontext = new BasicHttpContext(); HttpGet httpGet = new HttpGet(dhisURL.getPath() + endpoint); Credentials creds = new UsernamePasswordCredentials(user, pass); Header bs = new BasicScheme().authenticate(creds, httpGet, localcontext); httpGet.addHeader("Authorization", bs.getValue()); httpGet.addHeader("Content-Type", "application/json"); httpGet.addHeader("Accept", "application/json"); HttpResponse response = client.execute(targetHost, httpGet, localcontext); HttpEntity entity = response.getEntity(); if (entity != null && response.getStatusLine().getStatusCode() == 200) { payload = EntityUtils.toString(entity); saveToBackUp(endpoint, payload); } else { payload = getFromBackUp(endpoint); } } catch (Exception ex) { ex.printStackTrace(); payload = getFromBackUp(endpoint); } finally { if (client != null) { client.getConnectionManager().shutdown(); } } return payload; }
From source file:org.picketbox.test.authentication.http.jetty.DelegatingSecurityFilterHTTPDigestUnitTestCase.java
@Test public void testDigestAuth() throws Exception { URL url = new URL(urlStr); DefaultHttpClient httpclient = null; try {//w w w . j a v a 2 s.c o m String user = "Aladdin"; String pass = "Open Sesame"; httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url.toExternalForm()); HttpResponse response = httpclient.execute(httpget); assertEquals(401, response.getStatusLine().getStatusCode()); Header[] headers = response.getHeaders(PicketBoxConstants.HTTP_WWW_AUTHENTICATE); HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); Header header = headers[0]; String value = header.getValue(); value = value.substring(7).trim(); String[] tokens = HTTPDigestUtil.quoteTokenize(value); DigestHolder digestHolder = HTTPDigestUtil.digest(tokens); DigestScheme digestAuth = new DigestScheme(); digestAuth.overrideParamter("algorithm", "MD5"); digestAuth.overrideParamter("realm", digestHolder.getRealm()); digestAuth.overrideParamter("nonce", digestHolder.getNonce()); digestAuth.overrideParamter("qop", "auth"); digestAuth.overrideParamter("nc", "0001"); digestAuth.overrideParamter("cnonce", DigestScheme.createCnonce()); digestAuth.overrideParamter("opaque", digestHolder.getOpaque()); httpget = new HttpGet(url.toExternalForm()); Header auth = digestAuth.authenticate(new UsernamePasswordCredentials(user, pass), httpget); System.out.println(auth.getName()); System.out.println(auth.getValue()); httpget.setHeader(auth); System.out.println("executing request" + httpget.getRequestLine()); response = httpclient.execute(httpget); entity = response.getEntity(); System.out.println("----------------------------------------"); StatusLine statusLine = response.getStatusLine(); System.out.println(statusLine); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } assertEquals(200, statusLine.getStatusCode()); EntityUtils.consume(entity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }
From source file:org.apache.juddi.v3.client.mapping.wsdl.WSDLLocatorImpl.java
private InputSource getImportFromUrl(String url) { InputSource inputSource = null; DefaultHttpClient httpclient = null; try {// w w w . j ava 2 s .c om URL url2 = new URL(url); if (!url.toLowerCase().startsWith("http")) { return getImportFromFile(url); } boolean usessl = false; int port = 80; if (url.toLowerCase().startsWith("https://")) { port = 443; usessl = true; } if (url2.getPort() > 0) { port = url2.getPort(); } if (ignoreSSLErrors && usessl) { SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("https", port, new MockSSLSocketFactory())); ClientConnectionManager cm = new BasicClientConnectionManager(schemeRegistry); httpclient = new DefaultHttpClient(cm); } else { httpclient = new DefaultHttpClient(); } if (username != null && username.length() > 0 && password != null && password.length() > 0) { httpclient.getCredentialsProvider().setCredentials(new AuthScope(url2.getHost(), port), new UsernamePasswordCredentials(username, password)); } HttpGet httpGet = new HttpGet(url); try { HttpResponse response1 = httpclient.execute(httpGet); //System.out.println(response1.getStatusLine()); // HttpEntity entity1 = response1.getEntity(); // do something useful with the response body // and ensure it is fully consumed ResponseHandler<String> responseHandler = new BasicResponseHandler(); String handleResponse = responseHandler.handleResponse(response1); StringReader sr = new StringReader(handleResponse); inputSource = new InputSource(sr); } finally { httpGet.releaseConnection(); } // InputStream inputStream = importUrl.openStream(); //inputSource = new InputSource(inputStream); latestImportURI = url; } catch (Exception e) { log.error(e.getMessage()); log.debug(e.getMessage(), e); lastException = e; } finally { if (httpclient != null) { httpclient.getConnectionManager().shutdown(); } } return inputSource; }
From source file:com.mhise.util.MHISEUtil.java
public static String CallWebService(String url, String soapAction, String envelope, DefaultHttpClient httpClient) { // request parameters HttpParams params = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(params, 60000); HttpConnectionParams.setSoTimeout(params, 60000); // set parameter HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true); // POST the envelope HttpPost httppost = new HttpPost(url); // add headers httppost.setHeader("action", soapAction); httppost.setHeader("Content-Type", "application/soap+xml;charset=UTF-8;"); String responseString = ""; try {// w w w .j a va 2 s.c o m // the entity holds the request HttpEntity entity = new StringEntity(envelope); httppost.setEntity(entity); // Response handler ResponseHandler<String> rh = new ResponseHandler<String>() { // invoked when client receives response public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException { //Log.e("CallWebService",getResponseBody(response)); // get response entity HttpEntity entity = response.getEntity(); // read the response as byte array StringBuffer out = new StringBuffer(); byte[] b = EntityUtils.toByteArray(entity); String str = new String(b, 0, b.length); Log.e("string length", "" + str); //int index = b.length-1; //Log.e("b lase string",""+(char)(b[index-2])+(char)(b[index-1])+(char)(b[index])); // write the response byte array to a string buffer out.append(new String(b, 0, b.length)); return out.toString(); //return getResponseBody(response); } }; try { responseString = httpClient.execute(httppost, rh); } catch (Exception e) { Logger.debug("MHISEUtil-->CallWebService -->", "finally clause"); } } catch (Exception e) { Logger.debug("MHISEUtil-->CallWebService -->", "finally clause"); } // close the connection httpClient.getConnectionManager().closeExpiredConnections(); httpClient.getConnectionManager().shutdown(); Log.e("Response", "" + responseString); return responseString; }
From source file:com.lgallardo.qbittorrentclient.RSSFeedParser.java
public RSSFeed getRSSChannelInfo(String url) { // Parse url/*from w w w . ja v a 2 s . c o m*/ Uri uri = Uri.parse(url); int event; String text = null; String torrent = null; boolean header = true; HttpResponse httpResponse; DefaultHttpClient httpclient; XmlPullParserFactory xmlFactoryObject; XmlPullParser xmlParser = null; HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. int timeoutConnection = connection_timeout * 1000; // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = data_timeout * 1000; // Set http parameters HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpProtocolParams.setUserAgent(httpParameters, "qBittorrent for Android"); HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8); // Log.d("Debug", "Host: " + uri.getAuthority()); // Making HTTP request HttpHost targetHost = new HttpHost(uri.getAuthority()); // httpclient = new DefaultHttpClient(httpParameters); // httpclient = new DefaultHttpClient(); httpclient = getNewHttpClient(); httpclient.setParams(httpParameters); RSSFeed rssFeed = new RSSFeed(); try { // AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); // UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password); // // httpclient.getCredentialsProvider().setCredentials(authScope, credentials); // set http parameters HttpGet httpget = new HttpGet(url); httpResponse = httpclient.execute(targetHost, httpget); StatusLine statusLine = httpResponse.getStatusLine(); int mStatusCode = statusLine.getStatusCode(); if (mStatusCode != 200) { httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(mStatusCode); } HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); xmlFactoryObject = XmlPullParserFactory.newInstance(); xmlParser = xmlFactoryObject.newPullParser(); xmlParser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); xmlParser.setInput(is, null); event = xmlParser.getEventType(); // Get Channel info String name; RSSFeedItem item = null; List<RSSFeedItem> items = new ArrayList<RSSFeedItem>(); // Get items while (event != XmlPullParser.END_DOCUMENT && header) { name = xmlParser.getName(); switch (event) { case XmlPullParser.START_TAG: if (name != null && name.equals("item")) { header = false; } break; case XmlPullParser.TEXT: text = xmlParser.getText(); break; case XmlPullParser.END_TAG: if (name.equals("title")) { if (header) { rssFeed.setChannelTitle(text); } } else if (name.equals("description")) { if (header) { } } else if (name.equals("link")) { if (header) { rssFeed.setChannelLink(text); } } break; } event = xmlParser.next(); } is.close(); } catch (Exception e) { Log.e("Debug", "RSSFeedParser - : " + e.toString()); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } // return JSON String return rssFeed; }
From source file:org.picketbox.http.test.authentication.jetty.DelegatingSecurityFilterHTTPDigestUnitTestCase.java
@Test public void testDigestAuth() throws Exception { URL url = new URL(this.urlStr); DefaultHttpClient httpclient = null; try {/* w ww. jav a 2 s.c om*/ String user = "Aladdin"; String pass = "Open Sesame"; httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url.toExternalForm()); HttpResponse response = httpclient.execute(httpget); assertEquals(401, response.getStatusLine().getStatusCode()); Header[] headers = response.getHeaders(PicketBoxConstants.HTTP_WWW_AUTHENTICATE); HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); Header header = headers[0]; String value = header.getValue(); value = value.substring(7).trim(); String[] tokens = HTTPDigestUtil.quoteTokenize(value); Digest digestHolder = HTTPDigestUtil.digest(tokens); DigestScheme digestAuth = new DigestScheme(); digestAuth.overrideParamter("algorithm", "MD5"); digestAuth.overrideParamter("realm", digestHolder.getRealm()); digestAuth.overrideParamter("nonce", digestHolder.getNonce()); digestAuth.overrideParamter("qop", "auth"); digestAuth.overrideParamter("nc", "0001"); digestAuth.overrideParamter("cnonce", DigestScheme.createCnonce()); digestAuth.overrideParamter("opaque", digestHolder.getOpaque()); httpget = new HttpGet(url.toExternalForm()); Header auth = digestAuth.authenticate(new UsernamePasswordCredentials(user, pass), httpget); System.out.println(auth.getName()); System.out.println(auth.getValue()); httpget.setHeader(auth); System.out.println("executing request" + httpget.getRequestLine()); response = httpclient.execute(httpget); entity = response.getEntity(); System.out.println("----------------------------------------"); StatusLine statusLine = response.getStatusLine(); System.out.println(statusLine); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } assertEquals(200, statusLine.getStatusCode()); EntityUtils.consume(entity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }
From source file:sand.actionhandler.weibo.UdaClient.java
public static String download(String url, String filepath) { boolean ret = false; DefaultHttpClient httpclient = new DefaultHttpClient(); try {//from w w w.j a va 2 s . co m if (url.charAt(0) == '/') url = url.substring(1); File storeFile = new File(filepath); System.out.println(ActionHandler.OS_TYPE + "..................................."); if (ActionHandler.OS_TYPE.equalsIgnoreCase("windows")) { //storeFile = new File(filepath); storeFile = new File(_windowsLocation + filepath); } //File storeFile = new File("c:/root/udaclient/build/"+url); //logger.info(url+filepath); // ?? if (storeFile.exists()) { return "exists"; } httpclient = createHttpClient(); HttpGet httpget = new HttpGet(url + filepath); // Execute HTTP request // System.out.println("executing request " + httpget.getURI()); // logger.info("executing request " + httpget.getURI()); HttpResponse response = httpclient.execute(httpget); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); System.out.println(response.getLastHeader("Content-Encoding")); System.out.println(response.getLastHeader("Content-Length")); System.out.println("----------------------------------------"); HttpEntity entity = response.getEntity(); //if(entity.get) System.out.println(entity.getContentType()); // logger.info(entity.getContentType()); if (entity.getContentType().getValue().indexOf("text/html") >= 0) { return "error"; } org.apache.commons.io.FileUtils.touch(storeFile); FileOutputStream fileOutputStream = new FileOutputStream(storeFile); FileOutputStream output = fileOutputStream; entity.writeTo(output); output.close(); ret = true; // if (entity != null) { // content = EntityUtils.toString(entity); // System.out.println(content); // System.out.println("----------------------------------------"); // System.out.println("Uncompressed size: "+content.length()); // } } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } return "success"; }