List of usage examples for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider
public synchronized final CredentialsProvider getCredentialsProvider()
From source file:org.openml.knime.OpenMLWebservice.java
/** * Upload an implementation.//from w ww.j av a 2s . c o m * * * @param description Implementation description file * @param workflow Workflow file * @param user Name of the user * @param password Password of the user * @return Response from the server * @throws Exception If communication failed */ public static String sendImplementation(final File description, final File workflow, final String user, final String password) throws Exception { String result = ""; DefaultHttpClient httpclient = new DefaultHttpClient(); try { Credentials credentials = new UsernamePasswordCredentials(user, password); AuthScope scope = new AuthScope(new URI(WEBSERVICEURL).getHost(), 80); httpclient.getCredentialsProvider().setCredentials(scope, credentials); String url = WEBSERVICEURL + "?f=openml.implementation.upload"; HttpPost httppost = new HttpPost(url); MultipartEntity reqEntity = new MultipartEntity(); FileBody descBin = new FileBody(description); reqEntity.addPart("description", descBin); FileBody workflowBin = new FileBody(workflow); reqEntity.addPart("source", workflowBin); httppost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); if (response.getStatusLine().getStatusCode() < 200) { throw new Exception(response.getStatusLine().getReasonPhrase()); } if (resEntity != null) { result = convertStreamToString(resEntity.getContent()); } ErrorDocument errorDoc = null; try { errorDoc = ErrorDocument.Factory.parse(result); } catch (Exception e) { // no error XML should mean no error } if (errorDoc != null && errorDoc.validate()) { ErrorDocument.Error error = errorDoc.getError(); String errorMessage = error.getCode() + " : " + error.getMessage(); if (error.isSetAdditionalInformation()) { errorMessage += " : " + error.getAdditionalInformation(); } throw new Exception(errorMessage); } EntityUtils.consume(resEntity); } finally { try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) { // ignore } } return result; }
From source file:de.onyxbits.raccoon.gplay.PlayManager.java
/** * create a proxy client//from ww w .j a va2 s .co m * * @return either a client or null if none is configured * @throws KeyManagementException * @throws NumberFormatException * if that port could not be parsed. * @throws NoSuchAlgorithmException */ private static HttpClient createProxyClient(PlayProfile profile) throws KeyManagementException, NoSuchAlgorithmException { if (profile.getProxyAddress() == null) { return null; } PoolingClientConnectionManager connManager = new PoolingClientConnectionManager( SchemeRegistryFactory.createDefault()); connManager.setMaxTotal(100); connManager.setDefaultMaxPerRoute(30); DefaultHttpClient client = new DefaultHttpClient(connManager); client.getConnectionManager().getSchemeRegistry().register(Utils.getMockedScheme()); HttpHost proxy = new HttpHost(profile.getProxyAddress(), profile.getProxyPort()); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); if (profile.getProxyUser() != null && profile.getProxyPassword() != null) { client.getCredentialsProvider().setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials(profile.getProxyUser(), profile.getProxyPassword())); } return client; }
From source file:com.google.resting.rest.client.BaseRESTClient.java
protected static DefaultHttpClient buildHttpClient(ServiceContext serviceContext) { DefaultHttpClient httpClient = null; HttpParams httpParams = null;/*from w ww.jav a2 s . c om*/ HttpContext httpContext = serviceContext.getHttpContext(); Credentials credentials = null; if (httpContext != null) { httpParams = httpContext.getHttpParams(); credentials = httpContext.getCredentials(); } if (httpParams != null) httpClient = new DefaultHttpClient(httpParams); else httpClient = new DefaultHttpClient(); if (credentials != null) httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); return httpClient; }
From source file:org.sinekartads.integration.cms.SignCMSonAlfresco.java
public static <SkdsResponse extends BaseResponse> SkdsResponse postJsonRequest(BaseRequest request, Class<SkdsResponse> responseClass) throws IllegalStateException, IOException { SkdsResponse response = null;// w w w. j a v a2 s . c o m InputStream respIs = null; DefaultHttpClient httpclient = null; try { HttpHost targetHost = new HttpHost(HOST_NAME, PORT, "http"); httpclient = new DefaultHttpClient(); httpclient.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(USER, PWD)); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); HttpPost httppost = new HttpPost("/alfresco/service" + request.getJSONUrl() + ".json?requestType=json"); String req = request.toJSON(); ByteArrayEntity body = new ByteArrayEntity(req.getBytes()); httppost.setEntity(body); HttpResponse resp = httpclient.execute(targetHost, httppost, localcontext); HttpEntity entityResp = resp.getEntity(); respIs = entityResp.getContent(); response = TemplateUtils.Encoding.deserializeJSON(responseClass, respIs); EntityUtils.consume(entityResp); // } catch(Exception e) { // String message = e.getMessage(); // if ( StringUtils.isBlank(message) ) { // message = e.toString(); // } // tracer.error(message, e); // throw new RuntimeException(message, e); } finally { if (httpclient != null) { httpclient.getConnectionManager().shutdown(); } IOUtils.closeQuietly(respIs); } return response; }
From source file:org.sonar.ide.eclipse.wsclient.WSClientFactory.java
/** * Workaround for http://jira.codehaus.org/browse/SONAR-1586 *///w w w.ja v a2 s. c o m private static void configureProxy(DefaultHttpClient httpClient, Host server) { try { IProxyData proxyData = getEclipseProxyFor(server); if (proxyData != null && !IProxyData.SOCKS_PROXY_TYPE.equals(proxyData.getType())) { LOG.debug("Proxy for [{}] - [{}]", server.getHost(), proxyData); HttpHost proxy = new HttpHost(proxyData.getHost(), proxyData.getPort()); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); if (proxyData.isRequiresAuthentication()) { httpClient.getCredentialsProvider().setCredentials( new AuthScope(proxyData.getHost(), proxyData.getPort()), new UsernamePasswordCredentials(proxyData.getUserId(), proxyData.getPassword())); } } 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:longism.com.api.APIUtils.java
/** * TODO Function: Authenticate, login to sever<br> * * @param httpClient// w w w. j a va 2 s .c om * @param httpRequest * @param userName * @param password * @date: July 07, 2015 * @author: Nguyen Long */ public static void setAuthenticate(DefaultHttpClient httpClient, HttpUriRequest httpRequest, String userName, String password) { UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password); AuthScope scope = new AuthScope(httpRequest.getURI().getHost(), httpRequest.getURI().getPort()); httpClient.getCredentialsProvider().setCredentials(scope, credentials); }
From source file:com.cloudhopper.httpclient.util.HttpSender.java
static public Response postXml(String url, String username, String password, String requestXml) throws Exception { ////from w ww.j a va 2 s. c o m // trust any SSL connection // TrustManager easyTrustManager = new X509TrustManager() { public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException { // allow all } public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException { // allow all } public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } }; Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[] { easyTrustManager }, null); SSLSocketFactory sf = new SSLSocketFactory(sslcontext); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme https = new Scheme("https", sf, 443); //SchemeRegistry sr = new SchemeRegistry(); //sr.register(http); //sr.register(https); // create and initialize scheme registry //SchemeRegistry schemeRegistry = new SchemeRegistry(); //schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // create an HttpClient with the ThreadSafeClientConnManager. // This connection manager must be used if more than one thread will // be using the HttpClient. //ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry); //cm.setMaxTotalConnections(1); DefaultHttpClient client = new DefaultHttpClient(); client.getConnectionManager().getSchemeRegistry().register(https); HttpPost post = new HttpPost(url); StringEntity postEntity = new StringEntity(requestXml, "ISO-8859-1"); postEntity.setContentType("text/xml; charset=\"ISO-8859-1\""); post.addHeader("SOAPAction", "\"\""); post.setEntity(postEntity); long start = System.currentTimeMillis(); client.getCredentialsProvider().setCredentials(new AuthScope(null, AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password)); BasicHttpContext 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 interceptor client.addRequestInterceptor(new PreemptiveAuth(), 0); HttpResponse httpResponse = client.execute(post, localcontext); HttpEntity responseEntity = httpResponse.getEntity(); Response rsp = new Response(); // set the status line and reason rsp.statusCode = httpResponse.getStatusLine().getStatusCode(); rsp.statusLine = httpResponse.getStatusLine().getReasonPhrase(); // get an input stream rsp.body = EntityUtils.toString(responseEntity); // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources client.getConnectionManager().shutdown(); return rsp; }
From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.utils.HttpUtils.java
/** * @param config Gerrit Server Configuration. * @param url URL to get./* w ww. j a v a 2s. c o m*/ * @return httpresponse. * @throws IOException if found. */ public static HttpResponse performHTTPGet(IGerritHudsonTriggerConfig config, String url) throws IOException { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); if (config.getGerritProxy() != null && !config.getGerritProxy().isEmpty()) { try { URL proxyUrl = new URL(config.getGerritProxy()); HttpHost proxy = new HttpHost(proxyUrl.getHost(), proxyUrl.getPort(), proxyUrl.getProtocol()); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } catch (MalformedURLException e) { logger.error("Could not parse proxy URL, attempting without proxy.", e); } } httpclient.getCredentialsProvider().setCredentials(new AuthScope(null, -1), config.getHttpCredentials()); HttpResponse execute; return httpclient.execute(httpGet); }
From source file:lucee.commons.net.http.httpclient4.HTTPEngine4Impl.java
public static void setNTCredentials(DefaultHttpClient client, String username, String password, String workStation, String domain) { // set Username and Password if (!StringUtil.isEmpty(username, true)) { if (password == null) password = ""; CredentialsProvider cp = client.getCredentialsProvider(); cp.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new NTCredentials(username, password, workStation, domain)); //httpMethod.setDoAuthentication( true ); }/*from w w w. jav a2s . com*/ }
From source file:com.deliciousdroid.client.DeliciousApi.java
/** * Performs an api call to Delicious's http based api methods. * //from w w w . java 2 s. c om * @param url URL of the api method to call. * @param params Extra parameters included in the api call, as specified by different methods. * @param account The account being synced. * @param context The current application context. * @return A String containing the response from the server. * @throws IOException If a server error was encountered. * @throws AuthenticationException If an authentication error was encountered. */ private static InputStream DeliciousApiCall(String url, TreeMap<String, String> params, Account account, Context context) throws IOException, AuthenticationException { final AccountManager am = AccountManager.get(context); if (account == null) throw new AuthenticationException(); final String username = account.name; String authtoken = null; try { authtoken = am.blockingGetAuthToken(account, Constants.AUTHTOKEN_TYPE, false); } catch (OperationCanceledException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (AuthenticatorException e) { // TODO Auto-generated catch block e.printStackTrace(); } Uri.Builder builder = new Uri.Builder(); builder.scheme(SCHEME); builder.authority(DELICIOUS_AUTHORITY); builder.appendEncodedPath(url); for (String key : params.keySet()) { builder.appendQueryParameter(key, params.get(key)); } String apiCallUrl = builder.build().toString(); Log.d("apiCallUrl", apiCallUrl); final HttpGet post = new HttpGet(apiCallUrl); post.setHeader("User-Agent", "DeliciousDroid"); post.setHeader("Accept-Encoding", "gzip"); DefaultHttpClient client = (DefaultHttpClient) HttpClientFactory.getThreadSafeClient(); CredentialsProvider provider = client.getCredentialsProvider(); Credentials credentials = new UsernamePasswordCredentials(username, authtoken); provider.setCredentials(SCOPE, credentials); client.addRequestInterceptor(new PreemptiveAuthInterceptor(), 0); final HttpResponse resp = client.execute(post); final int statusCode = resp.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { final HttpEntity entity = resp.getEntity(); InputStream instream = entity.getContent(); final Header encoding = entity.getContentEncoding(); if (encoding != null && encoding.getValue().equalsIgnoreCase("gzip")) { instream = new GZIPInputStream(instream); } return instream; } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) { throw new AuthenticationException(); } else { throw new IOException(); } }