List of usage examples for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider
public synchronized final CredentialsProvider getCredentialsProvider()
From source file:dk.moerks.ratebeermobile.io.TwitterPoster.java
private HttpResponse postRequest(Context context, String url, List<NameValuePair> parameters) throws NetworkException { // Set up our own HttpClient DefaultHttpClient client = new DefaultHttpClient(new BasicHttpParams()); HttpPost post = new HttpPost(url); // Set RateBeer Mobile as twit source parameters.add(new BasicNameValuePair("source", SOURCE)); // Basic authentication of our Twitter user client.getCredentialsProvider().setCredentials(new AuthScope("api.twitter.com", 80), new UsernamePasswordCredentials(this.name, this.password)); try {/* w w w .j ava 2 s .c om*/ // Send POST request post.setEntity(new UrlEncodedFormEntity(parameters)); return client.execute(post); } catch (UnsupportedEncodingException e) { throw new NetworkException(context, LOGTAG, "Network Error - Cannot build Twitter request", e); } catch (ClientProtocolException e) { throw new NetworkException(context, LOGTAG, "Network Error - Cannot build Twitter request", e); } catch (IOException e) { throw new NetworkException(context, LOGTAG, "Network Error - Do you have a network connection?", e); } }
From source file:com.serotonin.m2m2.Common.java
public static HttpClient getHttpClient(int timeout) { DefaultHttpClient client = new DefaultHttpClient(); client.getParams().setParameter("http.socket.timeout", timeout); client.getParams().setParameter("http.connection.timeout", timeout); client.getParams().setParameter("http.connection-manager.timeout", timeout); client.getParams().setParameter("http.protocol.head-body-timeout", timeout); if (SystemSettingsDao.getBooleanValue(SystemSettingsDao.HTTP_CLIENT_USE_PROXY)) { String proxyHost = SystemSettingsDao.getValue(SystemSettingsDao.HTTP_CLIENT_PROXY_SERVER); int proxyPort = SystemSettingsDao.getIntValue(SystemSettingsDao.HTTP_CLIENT_PROXY_PORT); String username = SystemSettingsDao.getValue(SystemSettingsDao.HTTP_CLIENT_PROXY_USERNAME, ""); String password = SystemSettingsDao.getValue(SystemSettingsDao.HTTP_CLIENT_PROXY_PASSWORD, ""); client.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort), new UsernamePasswordCredentials(username, password)); }/* w w w . j a va2 s . c o m*/ return client; }
From source file:at.general.solutions.android.ical.remote.HttpDownloadThread.java
@Override public void run() { HttpParams params = new BasicHttpParams(); ConnManagerParams.setMaxTotalConnections(params, 100); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setUserAgent(params, USER_AGENT); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443)); ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); DefaultHttpClient client = new DefaultHttpClient(cm, params); if (useAuthentication) { client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(remoteUsername, remotePassword)); }/*from w ww .ja v a2 s .com*/ HttpGet get = new HttpGet(remoteUrl); try { super.sendInitMessage(R.string.downloading); HttpResponse response = client.execute(get); Log.d(LOG_TAG, response.getStatusLine().getReasonPhrase() + " " + isGoodResponse(response.getStatusLine().getStatusCode())); if (isGoodResponse(response.getStatusLine().getStatusCode())) { HttpEntity entity = response.getEntity(); InputStream instream = entity.getContent(); if (instream == null) { super.sendErrorMessage(R.string.couldnotConnectToRemoteserver); return; } if (entity.getContentLength() > Integer.MAX_VALUE) { super.sendErrorMessage(R.string.remoteFileTooLarge); return; } int i = (int) entity.getContentLength(); if (i < 0) { i = 4096; } String charset = EntityUtils.getContentCharSet(entity); if (charset == null) { charset = encoding; } if (charset == null) { charset = HTTP.DEFAULT_CONTENT_CHARSET; } Reader reader = new InputStreamReader(instream, charset); CharArrayBuffer buffer = new CharArrayBuffer(i); super.sendMaximumMessage(i); try { char[] tmp = new char[1024]; int l; while ((l = reader.read(tmp)) != -1) { buffer.append(tmp, 0, l); super.sendProgressMessage(buffer.length()); } } finally { reader.close(); } super.sendFinishedMessage(buffer.toString()); } else { int errorMsg = R.string.couldnotConnectToRemoteserver; if (isAccessDenied(response.getStatusLine().getStatusCode())) { errorMsg = R.string.accessDenied; } else if (isFileNotFound(response.getStatusLine().getStatusCode())) { errorMsg = R.string.remoteFileNotFound; } super.sendErrorMessage(errorMsg); } } catch (UnknownHostException e) { super.sendErrorMessage(R.string.unknownHostException, e); Log.e(LOG_TAG, "Error occured", e); } catch (Throwable e) { super.sendErrorMessage(R.string.couldnotConnectToRemoteserver, e); Log.e(LOG_TAG, "Error occured", e); } finally { client.getConnectionManager().shutdown(); } }
From source file:com.marvelution.hudson.plugins.apiv2.client.connectors.HttpClient4Connector.java
/** * Method to create the {@link HttpClient} * /* w w w. ja v a2 s.c o m*/ * @return the {@link DefaultHttpClient} */ private DefaultHttpClient createClient() { DefaultHttpClient client = new DefaultHttpClient(); if (server.isSecured()) { log.debug("The Server is secured, create the BasicHttpContext to handle preemptive authentication."); client.getCredentialsProvider().setCredentials(getAuthScope(), new UsernamePasswordCredentials(server.getUsername(), server.getPassword())); localContext = new BasicHttpContext(); // Generate BASIC scheme object and stick it to the local execution context BasicScheme basicAuth = new BasicScheme(); localContext.setAttribute("preemptive-auth", basicAuth); // Add as the first request intercepter client.addRequestInterceptor(new PreemptiveAuth(), 0); } if (StringUtils.isNotBlank(System.getProperty("http.proxyHost")) || StringUtils.isNotBlank(System.getProperty("https.proxyHost"))) { log.debug("A System HTTP(S) proxy is set, set the ProxySelectorRoutePlanner for the client"); System.setProperty("java.net.useSystemProxies", "true"); // Set the ProxySelectorRoute Planner to automatically select the system proxy host if set. client.setRoutePlanner(new ProxySelectorRoutePlanner(client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault())); } return client; }
From source file:gov.nrel.bacnet.consumer.DatabusSender.java
BasicHttpContext setupPreEmptiveBasicAuth(DefaultHttpClient httpclient) { HttpHost targetHost = new HttpHost(host, port, mode); httpclient.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(username, key)); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); // Add AuthCache to the execution context BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); return localcontext; }
From source file:com.jskj.asset.client.login.LoginTask.java
@Override protected Object doInBackground() throws Exception { try {//ww w.ja v a 2s . c om RestTemplate restTemplate = (RestTemplate) BeanFactory.instance().createBean(RestTemplate.class); if (logined) { ComResponse<String> com = restTemplate.getForObject( java.net.URI.create(Constants.HTTP + Constants.APPID + "logout"), ComResponse.class); if (com.getResponseStatus() != ComResponse.STATUS_OK) { return new Exception("logout failed. "); } else { BaseTreePane.disTabCount.clear(); } } Object userNameObj = map.get("userName"); ; Object passwdObj = map.get("userPassword"); HttpComponentsClientHttpRequestFactory httpRequestFactory = (HttpComponentsClientHttpRequestFactory) restTemplate .getRequestFactory(); DefaultHttpClient httpClient = (DefaultHttpClient) httpRequestFactory.getHttpClient(); String unicodeStr = UnicodeConverter.toEncodedUnicode(userNameObj.toString(), false); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(unicodeStr, passwdObj.toString()); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); UserSessionEntity session = restTemplate.getForObject(java.net.URI.create(URI), UserSessionEntity.class); return session; } catch (Exception e) { e.printStackTrace(); return e; } }
From source file:com.eviware.soapui.support.httpclient.JCIFSTest.java
@Test public void test() throws ParseException, IOException { try {/* ww w . j a v a 2 s . c o m*/ DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.getAuthSchemes().register(AuthPolicy.NTLM, new NTLMSchemeFactory()); httpClient.getAuthSchemes().register(AuthPolicy.SPNEGO, new NTLMSchemeFactory()); NTCredentials creds = new NTCredentials("testuser", "kebabsalladT357", "", ""); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds); HttpHost target = new HttpHost("dev-appsrv01.eviware.local", 81, "http"); HttpContext localContext = new BasicHttpContext(); HttpGet httpget = new HttpGet("/"); HttpResponse response1 = httpClient.execute(target, httpget, localContext); HttpEntity entity1 = response1.getEntity(); // System.out.println( "----------------------------------------" ); //System.out.println( response1.getStatusLine() ); // System.out.println( "----------------------------------------" ); if (entity1 != null) { //System.out.println( EntityUtils.toString( entity1 ) ); } // System.out.println( "----------------------------------------" ); // This ensures the connection gets released back to the manager EntityUtils.consume(entity1); Assert.assertEquals(response1.getStatusLine().getStatusCode(), 200); } catch (UnknownHostException e) { /* ignore */ } catch (HttpHostConnectException e) { /* ignore */ } catch (SocketException e) { /* ignore */ } Assert.assertTrue(true); }
From source file:cn.com.mozilla.sync.utils.HttpsTransport.java
public HttpResponse execHttpMethod(HttpRequestBase method, String userName, String passWord) throws IOException { DefaultHttpClient client = new DefaultHttpClient(mClientConMgr, sHttpParams); if (userName.length() > 0 && passWord.length() > 0) { Credentials defaultcreds = new UsernamePasswordCredentials(userName, passWord); client.getCredentialsProvider().setCredentials(AuthScope.ANY, defaultcreds); }// w w w . j a v a 2 s .c o m // retry 3 times DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(3, true); client.setHttpRequestRetryHandler(retryHandler); HttpResponse response = null; try { response = client.execute(method); } catch (IllegalStateException e) { // Deals with the situation that ClientConnectionManager shuts down during // connection throw new IOException(e.toString()); } return response; }
From source file:org.botlibre.util.Utils.java
public static String httpAuthGET(String url, String user, String password) throws Exception { HttpGet request = new HttpGet(url); DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(user, password)); HttpResponse response = client.execute(request); return fetchResponse(response); }
From source file:com.asakusafw.yaess.jobqueue.client.HttpJobClient.java
/** * Creates a new instance.//w w w .j av a 2s . c o m * @param baseUri the target base URL * @param user user name * @param password password * @throws IllegalArgumentException if some parameters were {@code null} */ public HttpJobClient(String baseUri, String user, String password) { if (baseUri == null) { throw new IllegalArgumentException("baseUri must not be null"); //$NON-NLS-1$ } if (user == null) { throw new IllegalArgumentException("user must not be null"); //$NON-NLS-1$ } if (password == null) { throw new IllegalArgumentException("password must not be null"); //$NON-NLS-1$ } this.baseUri = normalize(baseUri); this.user = user; DefaultHttpClient client = createClient(); client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password)); this.http = client; }