List of usage examples for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider
public synchronized final CredentialsProvider getCredentialsProvider()
From source file:com.sferadev.etic.tasks.DownloadTasksTask.java
private void updateTaskStatusToServer(FileDbAdapter fda, String source, String username, String password, String serverUrl) throws Exception { Log.i("updateTaskStatusToServer", "Enter"); Cursor taskListCursor = fda.fetchTasksForSource(source, false); taskListCursor.moveToFirst();/*from ww w .ja v a2s .c o m*/ DefaultHttpClient client = new DefaultHttpClient(); HttpResponse getResponse = null; // Add credentials if (username != null && password != null) { client.getCredentialsProvider().setCredentials(new AuthScope(null, -1, null), new UsernamePasswordCredentials(username, password)); } while (!taskListCursor.isAfterLast()) { if (isCancelled()) { return; } ; // Return if the user cancels String newStatus = taskListCursor.getString(taskListCursor.getColumnIndex(FileDbAdapter.KEY_T_STATUS)); String syncStatus = taskListCursor .getString(taskListCursor.getColumnIndex(FileDbAdapter.KEY_T_IS_SYNC)); long aid = taskListCursor.getLong(taskListCursor.getColumnIndex(FileDbAdapter.KEY_T_ASSIGNMENTID)); long tid = taskListCursor.getLong(taskListCursor.getColumnIndex(FileDbAdapter.KEY_T_ID)); Log.i("updateTaskStatusToServer", "aId:" + aid + " -- status:" + newStatus + " -- syncStatus:" + syncStatus); // Call the update service if (newStatus != null && syncStatus.equals(FileDbAdapter.STATUS_SYNC_NO)) { Log.i(getClass().getSimpleName(), "Updating server with status of " + aid + " to " + newStatus); Assignment a = new Assignment(); a.assignment_id = (int) aid; a.assignment_status = newStatus; // Call the service String taskURL = serverUrl + "/surveyKPI/myassignments/" + aid; HttpPost postRequest = new HttpPost(taskURL); ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); postParameters.add(new BasicNameValuePair("assignInput", "{assignment_status: " + newStatus + "}")); postRequest.setEntity(new UrlEncodedFormEntity(postParameters)); getResponse = client.execute(postRequest); int statusCode = getResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.w(getClass().getSimpleName(), "Error:" + statusCode + " for URL " + taskURL); } else { Log.w("updateTaskStatusToServer", "Status updated"); fda.setTaskSynchronized(tid); // Mark the task status as synchronised } } taskListCursor.moveToNext(); } taskListCursor.close(); }
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 w ww . j av a2 s .c om 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); }
From source file:de.wikilab.android.friendica01.TwAjax.java
private void setHttpClientProxy(DefaultHttpClient httpclient) { if (myProxyIp == null) return;//from ww w .jav a2 s. c o m httpclient.getCredentialsProvider().setCredentials(new AuthScope(myProxyIp, myProxyPort), new UsernamePasswordCredentials(myProxyUsername, myProxyPassword)); HttpHost proxy = new HttpHost(myProxyIp, myProxyPort); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); }
From source file:cm.aptoide.pt.RemoteInSearch.java
private String downloadFile(int position) { Vector<DownloadNode> tmp_serv = new Vector<DownloadNode>(); String getserv = new String(); String md5hash = null;// w w w.j av a 2s .c o m String repo = null; try { tmp_serv = db.getPathHash(apk_lst.get(position).apkid); if (tmp_serv.size() > 0) { DownloadNode node = tmp_serv.get(0); getserv = node.repo + "/" + node.path; md5hash = node.md5h; repo = node.repo; } if (getserv.length() == 0) throw new TimeoutException(); Message msg = new Message(); msg.arg1 = 0; msg.obj = new String(getserv); download_handler.sendMessage(msg); /*BufferedInputStream getit = new BufferedInputStream(new URL(getserv).openStream()); String path = new String(APK_PATH+apk_lst.get(position).name+".apk"); FileOutputStream saveit = new FileOutputStream(path); BufferedOutputStream bout = new BufferedOutputStream(saveit,1024); byte data[] = new byte[1024]; int readed = getit.read(data,0,1024); while(readed != -1) { bout.write(data,0,readed); readed = getit.read(data,0,1024); } bout.close(); getit.close(); saveit.close();*/ String path = new String(APK_PATH + apk_lst.get(position).name + ".apk"); FileOutputStream saveit = new FileOutputStream(path); DefaultHttpClient mHttpClient = new DefaultHttpClient(); HttpGet mHttpGet = new HttpGet(getserv); String[] logins = null; logins = db.getLogin(repo); if (logins != null) { URL mUrl = new URL(getserv); mHttpClient.getCredentialsProvider().setCredentials(new AuthScope(mUrl.getHost(), mUrl.getPort()), new UsernamePasswordCredentials(logins[0], logins[1])); } HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet); if (mHttpResponse.getStatusLine().getStatusCode() == 401) { return null; } else { byte[] buffer = EntityUtils.toByteArray(mHttpResponse.getEntity()); saveit.write(buffer); } File f = new File(path); Md5Handler hash = new Md5Handler(); if (md5hash == null || md5hash.equalsIgnoreCase(hash.md5Calc(f))) { return path; } else { return null; } } catch (Exception e) { return null; } }
From source file:my.madet.function.HttpParser.java
public String FetchUrL(String url) { StringBuffer result = new StringBuffer(); DefaultHttpClient httpclient = new DefaultHttpClient(); try {// w w w . jav a 2s . c o m // register ntlm auth scheme httpclient.getAuthSchemes().register("ntlm", new NTLMSchemeFactory()); httpclient.getCredentialsProvider().setCredentials( new AuthScope("info.uniten.edu.my", AuthScope.ANY_PORT), new NTCredentials(unitenid, unitenpassw, "", "")); HttpGet request = new HttpGet(url); HttpResponse httpResponse = httpclient.execute(request); BufferedReader br = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())); String line = ""; while ((line = br.readLine()) != null) { result.append(line); } br.close(); } catch (UnknownHostException e) { // no internet connection catch e.printStackTrace(); Log.e("FetchUrL", "No internet "); return "No_Internet"; } catch (Exception e) { Log.e("FetchUrL", "Error in http connection:" + e.toString()); return null; } String resultString = result.toString(); String regex = "(?i)<h1>Unauthorized Access</h1>"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(resultString); if (matcher.matches()) return "Unauthorized"; Log.i("FetchUrL content: ", result.toString()); return resultString; }
From source file:cm.aptoide.pt.DownloadQueueService.java
private void downloadFile(final int apkidHash) { try {//from w w w .ja va2 s . c om new Thread() { public void run() { this.setPriority(Thread.MAX_PRIORITY); if (!keepScreenOn.isHeld()) { keepScreenOn.acquire(); } int threadApkidHash = apkidHash; String remotePath = notifications.get(threadApkidHash).get("remotePath"); String md5hash = notifications.get(threadApkidHash).get("md5hash"); String localPath = notifications.get(threadApkidHash).get("localPath"); Log.d("Aptoide-DownloadQueuService", "thread apkidHash: " + threadApkidHash + " localPath: " + localPath); Message downloadArguments = new Message(); try { // If file exists, removes it... File f_chk = new File(localPath); if (f_chk.exists()) { f_chk.delete(); } f_chk = null; FileOutputStream saveit = new FileOutputStream(localPath); DefaultHttpClient mHttpClient = new DefaultHttpClient(); HttpGet mHttpGet = new HttpGet(remotePath); if (Boolean.parseBoolean(notifications.get(threadApkidHash).get("loginRequired"))) { URL mUrl = new URL(remotePath); mHttpClient.getCredentialsProvider().setCredentials( new AuthScope(mUrl.getHost(), mUrl.getPort()), new UsernamePasswordCredentials( notifications.get(threadApkidHash).get("username"), notifications.get(threadApkidHash).get("password"))); } HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet); if (mHttpResponse == null) { Log.d("Aptoide", "Problem in network... retry..."); mHttpResponse = mHttpClient.execute(mHttpGet); if (mHttpResponse == null) { Log.d("Aptoide", "Major network exception... Exiting!"); /*msg_al.arg1= 1; download_error_handler.sendMessage(msg_al);*/ throw new TimeoutException(); } } if (mHttpResponse.getStatusLine().getStatusCode() == 401) { throw new TimeoutException(); } else { InputStream getit = mHttpResponse.getEntity().getContent(); byte data[] = new byte[8096]; int red; red = getit.read(data, 0, 8096); int progressNotificationUpdate = 200; int intermediateProgress = 0; while (red != -1) { if (progressNotificationUpdate == 0) { if (!keepScreenOn.isHeld()) { keepScreenOn.acquire(); } progressNotificationUpdate = 200; Message progressArguments = new Message(); progressArguments.arg1 = threadApkidHash; progressArguments.arg2 = intermediateProgress; downloadProgress.sendMessage(progressArguments); intermediateProgress = 0; } else { intermediateProgress += red; progressNotificationUpdate--; } saveit.write(data, 0, red); red = getit.read(data, 0, 8096); } Log.d("Aptoide", "Download done! apkidHash: " + threadApkidHash + " localPath: " + localPath); saveit.flush(); saveit.close(); getit.close(); } if (keepScreenOn.isHeld()) { keepScreenOn.release(); } File f = new File(localPath); Md5Handler hash = new Md5Handler(); if (md5hash == null || md5hash.equalsIgnoreCase(hash.md5Calc(f))) { downloadArguments.arg1 = 1; downloadArguments.arg2 = threadApkidHash; downloadArguments.obj = localPath; downloadHandler.sendMessage(downloadArguments); } else { Log.d("Aptoide", md5hash + " VS " + hash.md5Calc(f)); downloadArguments.arg1 = 0; downloadArguments.arg2 = threadApkidHash; downloadErrorHandler.sendMessage(downloadArguments); } } catch (Exception e) { if (keepScreenOn.isHeld()) { keepScreenOn.release(); } downloadArguments.arg1 = 1; downloadArguments.arg2 = threadApkidHash; downloadErrorHandler.sendMessage(downloadArguments); } } }.start(); } catch (Exception e) { } }
From source file:org.sonar.ide.intellij.wsclient.WSClientFactory.java
/** * Workaround for http://jira.codehaus.org/browse/SONAR-1586 *//*w w w .j a v a2s. com*/ private void configureProxy(DefaultHttpClient httpClient, Host server) { try { Proxy proxyData = getIntelliJProxyFor(server); if (proxyData != null) { InetSocketAddress address = (InetSocketAddress) proxyData.address(); HttpConfigurable proxySettings = HttpConfigurable.getInstance(); LOG.debug("Proxy for [" + address.getHostName() + "] - [" + address + "]"); HttpHost proxy = new HttpHost(address.getHostName(), address.getPort()); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); if (proxySettings.PROXY_AUTHENTICATION) { httpClient.getCredentialsProvider().setCredentials( new AuthScope(address.getHostName(), address.getPort()), new UsernamePasswordCredentials(proxySettings.PROXY_LOGIN, proxySettings.getPlainProxyPassword())); } } else { LOG.debug("No proxy for [" + server.getHost() + "]"); } } catch (Exception e) { LOG.error("Unable to configure proxy for sonar-ws-client", e); } }
From source file:org.keycloak.testsuite.adapter.federation.AbstractKerberosAdapterTest.java
protected void initHttpClient(boolean useSpnego) { if (client != null) { after();/*w ww .ja v a 2 s. c o m*/ } DefaultHttpClient httpClient = (DefaultHttpClient) new HttpClientBuilder().build(); httpClient.getAuthSchemes().register(AuthPolicy.SPNEGO, spnegoSchemeFactory); if (useSpnego) { Credentials fake = new Credentials() { public String getPassword() { return null; } public Principal getUserPrincipal() { return null; } }; httpClient.getCredentialsProvider().setCredentials(new AuthScope(null, -1, null), fake); } ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient); client = new ResteasyClientBuilder().httpEngine(engine).build(); }
From source file:com.villemos.ispace.httpcrawler.HttpClientConfigurer.java
public static HttpClient setupClient(boolean ignoreAuthenticationFailure, String domain, Integer port, String proxyHost, Integer proxyPort, String authUser, String authPassword, CookieStore cookieStore) throws NoSuchAlgorithmException, KeyManagementException { DefaultHttpClient client = null; /** Always ignore authentication protocol errors. */ if (ignoreAuthenticationFailure) { SSLContext sslContext = SSLContext.getInstance("SSL"); // set up a TrustManager that trusts everything sslContext.init(null, new TrustManager[] { new EasyX509TrustManager() }, new SecureRandom()); SchemeRegistry schemeRegistry = new SchemeRegistry(); SSLSocketFactory sf = new SSLSocketFactory(sslContext); Scheme httpsScheme = new Scheme("https", sf, 443); schemeRegistry.register(httpsScheme); SocketFactory sfa = new PlainSocketFactory(); Scheme httpScheme = new Scheme("http", sfa, 80); schemeRegistry.register(httpScheme); HttpParams params = new BasicHttpParams(); ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry); client = new DefaultHttpClient(cm, params); } else {/*from w w w . j ava 2s.c o m*/ client = new DefaultHttpClient(); } if (proxyHost != null && proxyPort != null) { HttpHost proxy = new HttpHost(proxyHost, proxyPort); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } else { ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); client.setRoutePlanner(routePlanner); } /** The target location may demand authentication. We setup preemptive authentication. */ if (authUser != null && authPassword != null) { client.getCredentialsProvider().setCredentials(new AuthScope(domain, port), new UsernamePasswordCredentials(authUser, authPassword)); } /** Set default cookie policy and store. Can be overridden for a specific method using for example; * method.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); */ client.setCookieStore(cookieStore); // client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2965); client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); return client; }