List of usage examples for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider
public synchronized final CredentialsProvider getCredentialsProvider()
From source file:org.ancoron.osgi.test.glassfish.GlassfishDerbyTest.java
@Test(dependsOnGroups = { "glassfish-osgi-startup" }) public void testWebAvailability() throws NoSuchAlgorithmException, KeyManagementException, IOException { logTest();/*from w w w. j a va 2 s .co m*/ DefaultHttpClient http = getHTTPClient(); try { HttpGet httpget = new HttpGet("http://[::1]/movie/dummy/"); httpget.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); // Use HTTP 1.1 for this request only httpget.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE); HttpResponse res = http.execute(httpget); if (res.getStatusLine().getStatusCode() == 200) { fail("Gained access to secured page at '" + httpget.getURI().toASCIIString() + "' [status=" + res.getStatusLine().getStatusCode() + "]"); } log.log(Level.INFO, "[HTTP] Got response for ''{0}'' [status={1}]", new Object[] { httpget.getURI().toASCIIString(), res.getStatusLine().getStatusCode() }); HttpGet httpsget = new HttpGet("https://[::1]/movie/dummy/"); httpsget.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); // Use HTTP 1.1 for this request only httpsget.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE); res = http.execute(httpsget); if (res.getStatusLine().getStatusCode() == 200) { fail("Gained access to secured page at '" + httpsget.getURI().toASCIIString() + "' [status=" + res.getStatusLine().getStatusCode() + "] " + res.getStatusLine().getReasonPhrase()); } log.log(Level.INFO, "[HTTP] Got response for ''{0}'' [status={1}]", new Object[] { httpget.getURI().toASCIIString(), res.getStatusLine().getStatusCode() }); http.getCredentialsProvider().setCredentials(new AuthScope("[::1]", 8181), new UsernamePasswordCredentials("fail", "fail")); res = http.execute(httpsget); if (res.getStatusLine().getStatusCode() == 200) { fail("Gained access with invalid user role to secured page at '" + httpsget.getURI().toASCIIString() + "' [status=" + res.getStatusLine().getStatusCode() + "] " + res.getStatusLine().getReasonPhrase()); } log.log(Level.INFO, "[HTTP] Got response for ''{0}'' [status={1}]", new Object[] { httpget.getURI().toASCIIString(), res.getStatusLine().getStatusCode() }); http.getCredentialsProvider().setCredentials(new AuthScope("[::1]", 8181), new UsernamePasswordCredentials("test", "test")); res = http.execute(httpsget); if (res.getStatusLine().getStatusCode() != 200) { fail("Failed to access " + httpsget.getURI().toASCIIString() + ": [status=" + res.getStatusLine().getStatusCode() + "] " + res.getStatusLine().getReasonPhrase()); } log.log(Level.INFO, "[HTTP] Got response for ''{0}'' [status={1}]", new Object[] { httpget.getURI().toASCIIString(), res.getStatusLine().getStatusCode() }); } finally { http.getConnectionManager().shutdown(); } }
From source file:org.fcrepo.test.api.TestRESTAPI.java
private HttpClient getClient(boolean followRedirects, boolean auth) { DefaultHttpClient result = s_client.getHttpClient(followRedirects, auth); if (auth) {//from w ww. j a v a 2 s . c o m String host = getHost(); LOGGER.debug("credentials set for scope of {}:[ANY PORT]", host); result.getCredentialsProvider().setCredentials( new AuthScope(host, AuthScope.ANY_PORT, AuthScope.ANY_REALM), new UsernamePasswordCredentials(getUsername(), getPassword())); } else { result.getCredentialsProvider().clear(); } return result; }
From source file:net.wm161.microblog.lib.backends.statusnet.HTTPAPIRequest.java
protected String getData(URI location) throws APIException { Log.d("HTTPAPIRequest", "Downloading " + location); DefaultHttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(location); client.addRequestInterceptor(preemptiveAuth, 0); client.getParams().setBooleanParameter("http.protocol.expect-continue", false); if (!m_params.isEmpty()) { MultipartEntity params = new MultipartEntity(); for (Entry<String, Object> item : m_params.entrySet()) { Object value = item.getValue(); ContentBody data;/* www. ja v a 2 s .c o m*/ if (value instanceof Attachment) { Attachment attachment = (Attachment) value; try { data = new InputStreamBody(attachment.getStream(), attachment.contentType(), attachment.name()); Log.d("HTTPAPIRequest", "Found a " + attachment.contentType() + " attachment named " + attachment.name()); } catch (FileNotFoundException e) { getRequest().setError(ErrorType.ERROR_ATTACHMENT_NOT_FOUND); throw new APIException(); } catch (IOException e) { getRequest().setError(ErrorType.ERROR_ATTACHMENT_NOT_FOUND); throw new APIException(); } } else { try { data = new StringBody(value.toString()); } catch (UnsupportedEncodingException e) { getRequest().setError(ErrorType.ERROR_INTERNAL); throw new APIException(); } } params.addPart(item.getKey(), data); } post.setEntity(params); } UsernamePasswordCredentials creds = new UsernamePasswordCredentials(m_api.getAccount().getUser(), m_api.getAccount().getPassword()); client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds); HttpResponse req; try { req = client.execute(post); } catch (ClientProtocolException e3) { getRequest().setError(ErrorType.ERROR_CONNECTION_BROKEN); throw new APIException(); } catch (IOException e3) { getRequest().setError(ErrorType.ERROR_CONNECTION_FAILED); throw new APIException(); } InputStream result; try { result = req.getEntity().getContent(); } catch (IllegalStateException e1) { getRequest().setError(ErrorType.ERROR_INTERNAL); throw new APIException(); } catch (IOException e1) { getRequest().setError(ErrorType.ERROR_CONNECTION_BROKEN); throw new APIException(); } InputStreamReader in = null; int status; in = new InputStreamReader(result); status = req.getStatusLine().getStatusCode(); Log.d("HTTPAPIRequest", "Got status code of " + status); setStatusCode(status); if (status >= 300 || status < 200) { getRequest().setError(ErrorType.ERROR_SERVER); Log.w("HTTPAPIRequest", "Server code wasn't 2xx, got " + m_status); throw new APIException(); } int totalSize = -1; if (req.containsHeader("Content-length")) totalSize = Integer.parseInt(req.getFirstHeader("Content-length").getValue()); char[] buffer = new char[1024]; //2^17 = 131072. StringBuilder contents = new StringBuilder(131072); try { int size = 0; while ((totalSize > 0 && size < totalSize) || totalSize == -1) { int readSize = in.read(buffer); size += readSize; if (readSize == -1) break; if (totalSize >= 0) getRequest().publishProgress(new APIProgress((size / totalSize) * 5000)); contents.append(buffer, 0, readSize); } } catch (IOException e) { getRequest().setError(ErrorType.ERROR_CONNECTION_BROKEN); throw new APIException(); } return contents.toString(); }
From source file:cn.ctyun.amazonaws.http.HttpClientFactory.java
/** * Creates a new HttpClient object using the specified AWS * ClientConfiguration to configure the client. * * @param config/*from www . j a va2 s. c o m*/ * Client configuration options (ex: proxy settings, connection * limits, etc). * * @return The new, configured HttpClient. */ public HttpClient createHttpClient(ClientConfiguration config) { /* Set HTTP client parameters */ HttpParams httpClientParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpClientParams, config.getConnectionTimeout()); HttpConnectionParams.setSoTimeout(httpClientParams, config.getSocketTimeout()); HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, true); HttpConnectionParams.setTcpNoDelay(httpClientParams, true); int socketSendBufferSizeHint = config.getSocketBufferSizeHints()[0]; int socketReceiveBufferSizeHint = config.getSocketBufferSizeHints()[1]; if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) { HttpConnectionParams.setSocketBufferSize(httpClientParams, Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint)); } /* Set connection manager */ ThreadSafeClientConnManager connectionManager = ConnectionManagerFactory .createThreadSafeClientConnManager(config, httpClientParams); DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, httpClientParams); httpClient.setRedirectStrategy(new LocationHeaderNotRequiredRedirectStrategy()); try { Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory()); SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getDefault(), SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); Scheme https = new Scheme("https", 443, sf); SchemeRegistry sr = connectionManager.getSchemeRegistry(); sr.register(http); sr.register(https); } catch (NoSuchAlgorithmException e) { throw new AmazonClientException("Unable to access default SSL context", e); } /* * If SSL cert checking for endpoints has been explicitly disabled, * register a new scheme for HTTPS that won't cause self-signed certs to * error out. */ if (System.getProperty("com.amazonaws.sdk.disableCertChecking") != null) { Scheme sch = new Scheme("https", 443, new TrustingSocketFactory()); httpClient.getConnectionManager().getSchemeRegistry().register(sch); } /* Set proxy if configured */ String proxyHost = config.getProxyHost(); int proxyPort = config.getProxyPort(); if (proxyHost != null && proxyPort > 0) { AmazonHttpClient.log .info("Configuring Proxy. Proxy Host: " + proxyHost + " " + "Proxy Port: " + proxyPort); HttpHost proxyHttpHost = new HttpHost(proxyHost, proxyPort); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHttpHost); String proxyUsername = config.getProxyUsername(); String proxyPassword = config.getProxyPassword(); String proxyDomain = config.getProxyDomain(); String proxyWorkstation = config.getProxyWorkstation(); if (proxyUsername != null && proxyPassword != null) { httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain)); } } return httpClient; }
From source file:pt.lunacloud.http.HttpClientFactory.java
/** * Creates a new HttpClient object using the specified AWS * ClientConfiguration to configure the client. * * @param config/*from ww w .j a v a 2 s . c o m*/ * Client configuration options (ex: proxy settings, connection * limits, etc). * * @return The new, configured HttpClient. */ public HttpClient createHttpClient(ClientConfiguration config) { /* Form User-Agent information */ String userAgent = config.getUserAgent(); if (!(userAgent.equals(ClientConfiguration.DEFAULT_USER_AGENT))) { userAgent += ", " + ClientConfiguration.DEFAULT_USER_AGENT; } /* Set HTTP client parameters */ HttpParams httpClientParams = new BasicHttpParams(); HttpProtocolParams.setUserAgent(httpClientParams, userAgent); HttpConnectionParams.setConnectionTimeout(httpClientParams, config.getConnectionTimeout()); HttpConnectionParams.setSoTimeout(httpClientParams, config.getSocketTimeout()); HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, false); HttpConnectionParams.setTcpNoDelay(httpClientParams, true); int socketSendBufferSizeHint = config.getSocketBufferSizeHints()[0]; int socketReceiveBufferSizeHint = config.getSocketBufferSizeHints()[1]; if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) { HttpConnectionParams.setSocketBufferSize(httpClientParams, Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint)); } /* Set connection manager */ ThreadSafeClientConnManager connectionManager = ConnectionManagerFactory .createThreadSafeClientConnManager(config, httpClientParams); DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, httpClientParams); httpClient.setRedirectStrategy(new LocationHeaderNotRequiredRedirectStrategy()); try { Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory()); SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getDefault(), SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); Scheme https = new Scheme("https", 443, sf); SchemeRegistry sr = connectionManager.getSchemeRegistry(); sr.register(http); sr.register(https); } catch (NoSuchAlgorithmException e) { throw new LunacloudClientException("Unable to access default SSL context"); } /* * If SSL cert checking for endpoints has been explicitly disabled, * register a new scheme for HTTPS that won't cause self-signed certs to * error out. */ if (System.getProperty("com.amazonaws.sdk.disableCertChecking") != null) { Scheme sch = new Scheme("https", 443, new TrustingSocketFactory()); httpClient.getConnectionManager().getSchemeRegistry().register(sch); } /* Set proxy if configured */ String proxyHost = config.getProxyHost(); int proxyPort = config.getProxyPort(); if (proxyHost != null && proxyPort > 0) { AmazonHttpClient.log .info("Configuring Proxy. Proxy Host: " + proxyHost + " " + "Proxy Port: " + proxyPort); HttpHost proxyHttpHost = new HttpHost(proxyHost, proxyPort); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHttpHost); String proxyUsername = config.getProxyUsername(); String proxyPassword = config.getProxyPassword(); String proxyDomain = config.getProxyDomain(); String proxyWorkstation = config.getProxyWorkstation(); if (proxyUsername != null && proxyPassword != null) { httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain)); } } return httpClient; }
From source file:cm.aptoide.pt.ManageRepos.java
private returnStatus checkServerConnection(String uri, String user, String pwd) { Log.d("Aptoide-ManageRepo", "checking connection for: " + uri + " with credentials: " + user + " " + pwd); int result;//ww w .j a va2 s. com HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 10000); HttpConnectionParams.setSoTimeout(httpParameters, 10000); DefaultHttpClient mHttpClient = new DefaultHttpClient(httpParameters); // DefaultHttpClient mHttpClient = Threading.getThreadSafeHttpClient(); mHttpClient.setRedirectHandler(new RedirectHandler() { public boolean isRedirectRequested(HttpResponse response, HttpContext context) { return false; } public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException { return null; } }); HttpGet mHttpGet = new HttpGet(uri + "/info.xml"); // SharedPreferences sPref = this.getSharedPreferences("aptoide_prefs", Context.MODE_PRIVATE); // String myid = sPref.getString("myId", "NoInfo"); // String myscr = sPref.getInt("scW", 0)+"x"+sPref.getInt("scH", 0); // mHttpGet.setHeader("User-Agent", "aptoide-" + this.getString(R.string.ver_str)+";"+ Configs.TERMINAL_INFO+";"+myscr+";id:"+myid+";"+sPref.getString(Configs.LOGIN_USER_NAME, "")); try { if (user != null && pwd != null) { URL mUrl = new URL(uri); mHttpClient.getCredentialsProvider().setCredentials(new AuthScope(mUrl.getHost(), mUrl.getPort()), new UsernamePasswordCredentials(user, pwd)); } HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet); Header[] azz = mHttpResponse.getHeaders("Location"); if (azz.length > 0) { String newurl = azz[0].getValue(); mHttpGet = null; mHttpGet = new HttpGet(newurl); if (user != null && pwd != null) { URL mUrl = new URL(newurl); mHttpClient.getCredentialsProvider().setCredentials( new AuthScope(mUrl.getHost(), mUrl.getPort()), new UsernamePasswordCredentials(user, pwd)); } mHttpResponse = null; mHttpResponse = mHttpClient.execute(mHttpGet); } result = mHttpResponse.getStatusLine().getStatusCode(); if (result == 200) { return returnStatus.OK; } else if (result == 401) { return returnStatus.BAD_LOGIN; } else { return returnStatus.FAIL; } } catch (ClientProtocolException e) { return returnStatus.EXCEPTION; } catch (IOException e) { return returnStatus.EXCEPTION; } catch (IllegalArgumentException e) { return returnStatus.EXCEPTION; } catch (Exception e) { return returnStatus.EXCEPTION; } }
From source file:com.sferadev.etic.tasks.DownloadTasksTask.java
private void synchronise(boolean tasksEnabled) { Log.i("diag", "Synchronise()"); int count = 0; String taskURL = null;/*from w ww . ja v a 2 s . c om*/ fda.open(); fda.beginTransaction(); // Start Transaction // Get the source SharedPreferences settings = PreferenceManager .getDefaultSharedPreferences(Collect.getInstance().getBaseContext()); String serverUrl = Collect.getInstance().getString(R.string.default_server_url); String source = null; // Remove the protocol if (serverUrl.startsWith("http")) { int idx = serverUrl.indexOf("//"); if (idx > 0) { source = serverUrl.substring(idx + 2); } else { source = serverUrl; } } String username = settings.getString(PreferencesActivity.KEY_USERNAME, null); String password = settings.getString(PreferencesActivity.KEY_PASSWORD, null); Log.i("diag", "Source:" + source); if (source != null) { try { /* * Delete all entries in the database that are "Missed" or "Cancelled * These would have had their status set by the server the last time the user synchronised. * The user has seen their new status so time to remove. */ cleanupTasks(fda, source); /* * If tasks are enabled * Get tasks for this source from the database * Add to a hashmap indexed on the source's task id */ if (isCancelled()) { throw new CancelException("cancelled"); } ; // Return if the user cancels HttpResponse getResponse = null; DefaultHttpClient client = null; Gson gson = null; TaskResponse tr = null; int statusCode; if (tasksEnabled) { HashMap<String, TaskStatus> taskMap = new HashMap<String, TaskStatus>(); taskListCursor = fda.fetchTasksForSource(source, false); taskListCursor.moveToFirst(); while (!taskListCursor.isAfterLast()) { if (isCancelled()) { throw new CancelException("cancelled"); } ; // Return if the user cancels String status = taskListCursor .getString(taskListCursor.getColumnIndex(FileDbAdapter.KEY_T_STATUS)); String aid = taskListCursor .getString(taskListCursor.getColumnIndex(FileDbAdapter.KEY_T_ASSIGNMENTID)); long tid = taskListCursor.getLong(taskListCursor.getColumnIndex(FileDbAdapter.KEY_T_ID)); TaskStatus t = new TaskStatus(tid, status); taskMap.put(aid, t); Log.i(getClass().getSimpleName(), "Current task:" + aid + " status:" + status); taskListCursor.moveToNext(); } taskListCursor.close(); // Get the tasks for this source from the server client = new DefaultHttpClient(); // Add credentials if (username != null && password != null) { client.getCredentialsProvider().setCredentials(new AuthScope(null, -1, null), new UsernamePasswordCredentials(username, password)); } if (isCancelled()) { throw new CancelException("cancelled"); } ; // Return if the user cancels // Call the service taskURL = serverUrl + "/surveyKPI/myassignments"; InputStream is = null; HttpGet getRequest = new HttpGet(taskURL); getResponse = client.execute(getRequest); statusCode = getResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.w(getClass().getSimpleName(), "Error:" + statusCode + " for URL " + taskURL); throw new Exception("Error connecting - check username and password"); } else { HttpEntity getResponseEntity = getResponse.getEntity(); is = getResponseEntity.getContent(); } // De-serialise gson = new GsonBuilder().setDateFormat("dd/MM/yyyy hh:mm").create(); Reader isReader = new InputStreamReader(is); tr = gson.fromJson(isReader, TaskResponse.class); Log.i(getClass().getSimpleName(), "Message:" + tr.message); /* * Loop through the entries from the source * (1) Add entries that have a status of "new", "pending" or "accepted" and are not already on the phone * (2) Update the status of database entries where the source status is set to "Missed" or "Cancelled" */ count += addAndUpdateEntries(tr, fda, taskMap, username, source); } /* * Loop through the entries in the database * (1) Update on the server all that have a status of "accepted", "rejected" or "submitted" or "cancelled" or "completed" * Note in the case of "cancelled" the client is merely acknowledging that it received the cancellation notice */ if (isCancelled()) { throw new CancelException("cancelled"); } ; // Return if the user cancels if (tasksEnabled) { updateTaskStatusToServer(fda, source, username, password, serverUrl); } /* * Delete all orphaned tasks (The instance has been deleted) */ taskListCursor = fda.fetchAllTasks(); taskListCursor.moveToFirst(); while (!taskListCursor.isAfterLast()) { if (isCancelled()) { throw new CancelException("cancelled"); } ; // Return if the user cancels String instancePath = taskListCursor .getString(taskListCursor.getColumnIndex(FileDbAdapter.KEY_T_INSTANCE)); long tid = taskListCursor.getLong(taskListCursor.getColumnIndex(FileDbAdapter.KEY_T_ID)); Log.i(getClass().getSimpleName(), "Instance:" + instancePath); // Delete the task if the instance has been deleted if (!instanceExists(instancePath)) { fda.deleteTask(tid); } taskListCursor.moveToNext(); } taskListCursor.close(); /* * Delete all entries in the database that are "Submitted" or "Rejected" * The user set these status values, no need to keep the tasks */ fda.deleteTasksFromSource(source, FileDbAdapter.STATUS_T_REJECTED); fda.deleteTasksFromSource(source, FileDbAdapter.STATUS_T_SUBMITTED); // Commit the transation fda.setTransactionSuccessful(); // Commit the transaction } catch (JsonSyntaxException e) { Log.e(getClass().getSimpleName(), "JSON Syntax Error:" + " for URL " + taskURL); publishProgress(e.getMessage()); e.printStackTrace(); results.put("Error:", e.getMessage()); } catch (CancelException e) { Log.i(getClass().getSimpleName(), "Info: Download cancelled by user."); } catch (Exception e) { Log.e(getClass().getSimpleName(), "Error:" + " for URL " + taskURL); e.printStackTrace(); publishProgress(e.getMessage()); results.put("Error:", e.getMessage()); } finally { if (fda != null) { fda.endTransaction(); fda.close(); } if (taskListCursor != null) { taskListCursor.close(); taskListCursor = null; } } } if (count == 0) { results.put("err_no_tasks", ""); } }