List of usage examples for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider
public synchronized final CredentialsProvider getCredentialsProvider()
From source file:com.amalto.workbench.utils.HttpClientUtil.java
private static DefaultHttpClient wrapAuthClient(String url, String username, String password) throws SecurityException { DefaultHttpClient client = createClient(); URI uri = URI.create(url); AuthScope authScope = new AuthScope(uri.getHost(), uri.getPort()); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); client.getCredentialsProvider().setCredentials(authScope, credentials); return client; }
From source file:ca.sqlpower.wabit.enterprise.client.WabitClientSession.java
public static HttpClient createHttpClient(SPServerInfo serviceInfo) { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 2000); DefaultHttpClient httpClient = new DefaultHttpClient(params); httpClient.setCookieStore(cookieStore); httpClient.getCredentialsProvider().setCredentials( new AuthScope(serviceInfo.getServerAddress(), AuthScope.ANY_PORT), new UsernamePasswordCredentials(serviceInfo.getUsername(), serviceInfo.getPassword())); return httpClient; }
From source file:org.megam.deccanplato.http.TransportMachinery.java
public static TransportResponse post(TransportTools nuts) throws ClientProtocolException, IOException { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(nuts.urlString()); System.out.println("NUTS" + nuts.toString()); if (nuts.headers() != null) { for (Map.Entry<String, String> headerEntry : nuts.headers().entrySet()) { //this if condition is set for twilio Rest API to add credentials to DefaultHTTPClient, conditions met twilio work. if (headerEntry.getKey().equalsIgnoreCase("provider") & headerEntry.getValue().equalsIgnoreCase(nuts.headers().get("provider"))) { httpclient.getCredentialsProvider().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials( nuts.headers().get("account_sid"), nuts.headers().get("oauth_token"))); }/* w w w. j av a 2 s .c o m*/ //this else part statements for other providers else { httppost.addHeader(headerEntry.getKey(), headerEntry.getValue()); } } } if (nuts.fileEntity() != null) { httppost.setEntity(nuts.fileEntity()); } if (nuts.pairs() != null && (nuts.contentType() == null)) { httppost.setEntity(new UrlEncodedFormEntity(nuts.pairs())); } if (nuts.contentType() != null) { httppost.setEntity(new StringEntity(nuts.contentString(), nuts.contentType())); } TransportResponse transportResp = null; System.out.println(httppost.toString()); try { HttpResponse httpResp = httpclient.execute(httppost); transportResp = new TransportResponse(httpResp.getStatusLine(), httpResp.getEntity(), httpResp.getLocale()); } finally { httppost.releaseConnection(); } return transportResp; }
From source file:com.amazonaws.eclipse.core.HttpClientFactory.java
private static void configureProxy(DefaultHttpClient client, String url) { AwsToolkitCore plugin = AwsToolkitCore.getDefault(); if (plugin != null) { IProxyService proxyService = AwsToolkitCore.getDefault().getProxyService(); if (proxyService.isProxiesEnabled()) { try { IProxyData[] proxyData;//from w ww.j a va 2s. co m proxyData = proxyService.select(new URI(url)); if (proxyData.length > 0) { IProxyData data = proxyData[0]; client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(data.getHost(), data.getPort())); if (data.isRequiresAuthentication()) { client.getCredentialsProvider().setCredentials( new AuthScope(data.getHost(), data.getPort()), new NTCredentials(data.getUserId(), data.getPassword(), null, null)); } } } catch (URISyntaxException e) { plugin.getLog().log(new Status(Status.ERROR, AwsToolkitCore.PLUGIN_ID, e.getMessage(), e)); } } } }
From source file:org.bibalex.gallery.storage.BAGStorage.java
public static boolean putFile(String remoteUrlStr, File localFile, String contentType, int timeout) throws BAGException { HttpPut httpput = null;// w w w .ja v a2 s . co m DefaultHttpClient httpclient = null; try { BasicHttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, timeout); httpclient = new DefaultHttpClient(httpParams); URI remoteUrl = new URI(remoteUrlStr); String userInfo = remoteUrl.getUserInfo(); if ((userInfo != null) && !userInfo.isEmpty()) { int colonIx = userInfo.indexOf(':'); httpclient.getCredentialsProvider().setCredentials( new AuthScope(remoteUrl.getHost(), remoteUrl.getPort()), new UsernamePasswordCredentials( userInfo.substring(0, colonIx), userInfo.substring(colonIx + 1))); } if ((contentType == null) || contentType.isEmpty()) { contentType = "text/plain; charset=\"UTF-8\""; } FileEntity entity = new FileEntity(localFile, contentType); httpput = new HttpPut(remoteUrlStr); httpput.setEntity(entity); HttpResponse response = httpclient.execute(httpput); return response.getStatusLine().getStatusCode() - 200 < 100; } catch (IOException ex) { // In case of an IOException the connection will be released // back to the connection manager automatically throw new BAGException(ex); } catch (RuntimeException ex) { // In case of an unexpected exception you may want to abort // the HTTP request in order to shut down the underlying // connection and release it back to the connection manager. httpput.abort(); throw ex; } catch (URISyntaxException e) { // will be still null: httpput.abort(); throw new BAGException(e); } 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.jboss.jdf.stacks.StacksFactory.java
private static void configureProxy(final DefaultHttpClient client, final StacksConfiguration stacksConfig) { if (stacksConfig.getProxyHost() != null) { final String proxyHost = stacksConfig.getProxyHost(); final int proxyPort = stacksConfig.getProxyPort(); final HttpHost proxy = new HttpHost(proxyHost, proxyPort); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); final String proxyUsername = stacksConfig.getProxyUser(); if (proxyUsername != null && !proxyUsername.isEmpty()) { final String proxyPassword = stacksConfig.getProxyPassword(); final AuthScope authScope = new AuthScope(proxyHost, proxyPort); final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(proxyUsername, proxyPassword);/*from w ww.j ava 2s . c o m*/ client.getCredentialsProvider().setCredentials(authScope, credentials); } } }
From source file:org.jboss.as.test.integration.management.interfaces.HttpManagementInterface.java
private static HttpClient createHttpClient(String host, int port, String username, String password) { PoolingClientConnectionManager connectionPool = new PoolingClientConnectionManager(); DefaultHttpClient httpClient = new DefaultHttpClient(connectionPool); SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); try {/*ww w . j a v a 2 s . c o m*/ schemeRegistry.register(new Scheme("https", 443, new SSLSocketFactory(new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }, new AllowAllHostnameVerifier()))); } catch (Exception e) { throw new RuntimeException(e); } httpClient.setHttpRequestRetryHandler(new StandardHttpRequestRetryHandler(5, true)); httpClient.getCredentialsProvider().setCredentials( new AuthScope(host, port, MANAGEMENT_REALM, AuthPolicy.DIGEST), new UsernamePasswordCredentials(username, password)); return httpClient; }
From source file:com.vuze.android.remote.rpc.RestJsonClient.java
public static Map<?, ?> connect(String id, String url, Map<?, ?> jsonPost, Header[] headers, UsernamePasswordCredentials creds, boolean sendGzip) throws RPCException { long readTime = 0; long connSetupTime = 0; long connTime = 0; int bytesRead = 0; if (DEBUG_DETAILED) { Log.d(TAG, id + "] Execute " + url); }// www . j a va 2 s.co m long now = System.currentTimeMillis(); long then; Map<?, ?> json = Collections.EMPTY_MAP; try { URI uri = new URI(url); int port = uri.getPort(); BasicHttpParams basicHttpParams = new BasicHttpParams(); HttpProtocolParams.setUserAgent(basicHttpParams, "Vuze Android Remote"); DefaultHttpClient httpclient; if ("https".equals(uri.getScheme())) { httpclient = MySSLSocketFactory.getNewHttpClient(port); } else { httpclient = new DefaultHttpClient(basicHttpParams); } //AndroidHttpClient.newInstance("Vuze Android Remote"); // This doesn't set the "Authorization" header!? httpclient.getCredentialsProvider().setCredentials(new AuthScope(null, -1), creds); // Prepare a request object HttpRequestBase httpRequest = jsonPost == null ? new HttpGet(uri) : new HttpPost(uri); // IllegalArgumentException if (creds != null) { byte[] toEncode = (creds.getUserName() + ":" + creds.getPassword()).getBytes(); String encoding = Base64Encode.encodeToString(toEncode, 0, toEncode.length); httpRequest.setHeader("Authorization", "Basic " + encoding); } if (jsonPost != null) { HttpPost post = (HttpPost) httpRequest; String postString = JSONUtils.encodeToJSON(jsonPost); if (AndroidUtils.DEBUG_RPC) { Log.d(TAG, id + "] Post: " + postString); } AbstractHttpEntity entity = (sendGzip && Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) ? getCompressedEntity(postString) : new StringEntity(postString); post.setEntity(entity); post.setHeader("Accept", "application/json"); post.setHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8"); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { setupRequestFroyo(httpRequest); } if (headers != null) { for (Header header : headers) { httpRequest.setHeader(header); } } // Execute the request HttpResponse response; then = System.currentTimeMillis(); if (AndroidUtils.DEBUG_RPC) { connSetupTime = (then - now); now = then; } httpclient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException e, int i, HttpContext httpContext) { if (i < 2) { return true; } return false; } }); response = httpclient.execute(httpRequest); then = System.currentTimeMillis(); if (AndroidUtils.DEBUG_RPC) { connTime = (then - now); now = then; } HttpEntity entity = response.getEntity(); // XXX STATUSCODE! StatusLine statusLine = response.getStatusLine(); if (AndroidUtils.DEBUG_RPC) { Log.d(TAG, "StatusCode: " + statusLine.getStatusCode()); } if (entity != null) { long contentLength = entity.getContentLength(); if (contentLength >= Integer.MAX_VALUE - 2) { throw new RPCException("JSON response too large"); } // A Simple JSON Response Read InputStream instream = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) ? getUngzippedContent(entity) : entity.getContent(); InputStreamReader isr = new InputStreamReader(instream, "utf8"); StringBuilder sb = null; BufferedReader br = null; // JSONReader is 10x slower, plus I get more OOM errors.. :( // final boolean useStringBuffer = contentLength > (4 * 1024 * 1024) ? false // : DEFAULT_USE_STRINGBUFFER; final boolean useStringBuffer = DEFAULT_USE_STRINGBUFFER; if (useStringBuffer) { // Setting capacity saves StringBuffer from going through many // enlargeBuffers, and hopefully allows toString to not make a copy sb = new StringBuilder(contentLength > 512 ? (int) contentLength + 2 : 512); } else { if (AndroidUtils.DEBUG_RPC) { Log.d(TAG, "Using BR. ContentLength = " + contentLength); } br = new BufferedReader(isr, 8192); br.mark(32767); } try { // 9775 files on Nexus 7 (~2,258,731 bytes) // fastjson 1.1.46 (String) : 527- 624ms // fastjson 1.1.39 (String) : 924-1054ms // fastjson 1.1.39 (StringBuilder): 1227-1463ms // fastjson 1.1.39 (BR) : 2233-2260ms // fastjson 1.1.39 (isr) : 2312ms // GSON 2.2.4 (String) : 1539-1760ms // GSON 2.2.4 (BufferedReader) : 2646-3060ms // JSON-SMART 1.3.1 (String) : 572- 744ms (OOMs more often than fastjson) if (useStringBuffer) { char c[] = new char[8192]; while (true) { int read = isr.read(c); if (read < 0) { break; } sb.append(c, 0, read); } if (AndroidUtils.DEBUG_RPC) { then = System.currentTimeMillis(); if (DEBUG_DETAILED) { if (sb.length() > 2000) { Log.d(TAG, id + "] " + sb.substring(0, 2000) + "..."); } else { Log.d(TAG, id + "] " + sb.toString()); } } bytesRead = sb.length(); readTime = (then - now); now = then; } json = JSONUtils.decodeJSON(sb.toString()); //json = JSONUtilsGSON.decodeJSON(sb.toString()); } else { //json = JSONUtils.decodeJSON(isr); json = JSONUtils.decodeJSON(br); //json = JSONUtilsGSON.decodeJSON(br); } } catch (Exception pe) { // StatusLine statusLine = response.getStatusLine(); if (statusLine != null && statusLine.getStatusCode() == 409) { throw new RPCException(response, "409"); } try { String line; if (useStringBuffer) { line = sb.subSequence(0, Math.min(128, sb.length())).toString(); } else { br.reset(); line = br.readLine().trim(); } isr.close(); if (AndroidUtils.DEBUG_RPC) { Log.d(TAG, id + "]line: " + line); } Header contentType = entity.getContentType(); if (line.startsWith("<") || line.contains("<html") || (contentType != null && contentType.getValue().startsWith("text/html"))) { // TODO: use android strings.xml throw new RPCException(response, "Could not retrieve remote client location information. The most common cause is being on a guest wifi that requires login before using the internet."); } } catch (IOException ignore) { } Log.e(TAG, id, pe); if (statusLine != null) { String msg = statusLine.getStatusCode() + ": " + statusLine.getReasonPhrase() + "\n" + pe.getMessage(); throw new RPCException(msg, pe); } throw new RPCException(pe); } finally { closeOnNewThread(useStringBuffer ? isr : br); } if (AndroidUtils.DEBUG_RPC) { // Log.d(TAG, id + "]JSON Result: " + json); } } } catch (RPCException e) { throw e; } catch (Throwable e) { Log.e(TAG, id, e); throw new RPCException(e); } if (AndroidUtils.DEBUG_RPC) { then = System.currentTimeMillis(); Log.d(TAG, id + "] conn " + connSetupTime + "/" + connTime + "ms. Read " + bytesRead + " in " + readTime + "ms, parsed in " + (then - now) + "ms"); } return json; }
From source file:de.javakaffee.web.msm.integration.TestUtils.java
private static HttpResponse executeRequestWithAuth(final DefaultHttpClient client, final HttpUriRequest method, final Credentials credentials) throws IOException, ClientProtocolException { client.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); final BasicHttpContext localcontext = new BasicHttpContext(); // Generate BASIC scheme object and stick it to the local // execution context final BasicScheme basicAuth = new BasicScheme(); localcontext.setAttribute("preemptive-auth", basicAuth); // System.out.println( "cookies: " + method.getParams().getCookiePolicy() ); //method.getParams().setCookiePolicy(CookiePolicy.RFC_2109); return client.execute(method, localcontext); }
From source file:de.unikassel.android.sdcframework.transmission.BasicAuthHttpProtocol.java
@Override protected final void configureForAuthentication(DefaultHttpClient client, URL url) { client.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), -1), new UsernamePasswordCredentials(getUserName(), getMd5Password())); }