List of usage examples for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider
public synchronized final CredentialsProvider getCredentialsProvider()
From source file:org.jboss.jdf.stacks.client.StacksClient.java
private void configureProxy(DefaultHttpClient client) { if (actualConfiguration.getProxyHost() != null && !actualConfiguration.getProxyHost().isEmpty()) { String proxyHost = actualConfiguration.getProxyHost(); int proxyPort = actualConfiguration.getProxyPort(); HttpHost proxy = new HttpHost(proxyHost, proxyPort); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); String proxyUsername = actualConfiguration.getProxyUser(); if (proxyUsername != null && !proxyUsername.isEmpty()) { String proxyPassword = actualConfiguration.getProxyPassword(); AuthScope authScope = new AuthScope(proxyHost, proxyPort); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(proxyUsername, proxyPassword);//from w w w . ja v a2 s . com client.getCredentialsProvider().setCredentials(authScope, credentials); } } }
From source file:com.aliyun.oss.common.comm.HttpClientFactory.java
public HttpClient createHttpClient(ClientConfiguration config) { HttpParams httpClientParams = new BasicHttpParams(); HttpProtocolParams.setUserAgent(httpClientParams, config.getUserAgent()); HttpConnectionParams.setConnectionTimeout(httpClientParams, config.getConnectionTimeout()); HttpConnectionParams.setSoTimeout(httpClientParams, config.getSocketTimeout()); HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, true); HttpConnectionParams.setTcpNoDelay(httpClientParams, true); PoolingClientConnectionManager connManager = createConnectionManager(config, httpClientParams); DefaultHttpClient httpClient = new DefaultHttpClient(connManager, httpClientParams); if (System.getProperty("com.aliyun.oss.disableCertChecking") != null) { Scheme sch = new Scheme("https", 443, getSSLSocketFactory()); httpClient.getConnectionManager().getSchemeRegistry().register(sch); }/*from ww w .j a v a2 s .co m*/ String proxyHost = config.getProxyHost(); int proxyPort = config.getProxyPort(); if (proxyHost != null && proxyPort > 0) { HttpHost proxy = new HttpHost(proxyHost, proxyPort); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); String proxyUsername = config.getProxyUsername(); String proxyPassword = config.getProxyPassword(); if (proxyUsername != null && proxyPassword != null) { String proxyDomain = config.getProxyDomain(); String proxyWorkstation = config.getProxyWorkstation(); httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain)); } } return httpClient; }
From source file:org.jboss.maven.plugins.qstools.config.ConfigurationProvider.java
private void configureProxy(DefaultHttpClient client) { Proxy proxyConfig = null;/*from w w w . ja v a 2 s . c o m*/ if (mavenSession.getSettings().getProxies().size() > 0) { proxyConfig = mavenSession.getSettings().getProxies().get(0); } if (proxyConfig != null) { HttpHost proxy = new HttpHost(proxyConfig.getHost(), proxyConfig.getPort()); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); String proxyUsername = proxyConfig.getUsername(); if (proxyUsername != null && !proxyUsername.isEmpty()) { String proxyPassword = proxyConfig.getPassword(); AuthScope authScope = new AuthScope(proxyConfig.getHost(), proxyConfig.getPort()); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(proxyUsername, proxyPassword); client.getCredentialsProvider().setCredentials(authScope, credentials); } } }
From source file:net.java.sip.communicator.service.httputil.HttpUtils.java
/** * Posting form to <tt>address</tt>. For submission we use POST method * which is "application/x-www-form-urlencoded" encoded. * @param httpClient the http client/*w w w . j a v a2 s . c o m*/ * @param postMethod the post method * @param address HTTP address. * @param formParamNames the parameter names to include in post. * @param formParamValues the corresponding parameter values to use. * @param usernameParamIx the index of the username parameter in the * <tt>formParamNames</tt> and <tt>formParamValues</tt> * if any, otherwise -1. * @param passwordParamIx the index of the password parameter in the * <tt>formParamNames</tt> and <tt>formParamValues</tt> * if any, otherwise -1. * @param headerParamNames additional header name to include * @param headerParamValues corresponding header value to include * @return the result or null if send was not possible or * credentials ask if any was canceled. */ private static HttpEntity postForm(DefaultHttpClient httpClient, HttpPost postMethod, String address, ArrayList<String> formParamNames, ArrayList<String> formParamValues, int usernameParamIx, int passwordParamIx, RedirectHandler redirectHandler, List<String> headerParamNames, List<String> headerParamValues) throws Throwable { // if we have username and password in the parameters, lets // retrieve their values // if there are already filled skip asking the user Credentials creds = null; if (usernameParamIx != -1 && usernameParamIx < formParamNames.size() && passwordParamIx != -1 && passwordParamIx < formParamNames.size() && (formParamValues.get(usernameParamIx) == null || formParamValues.get(usernameParamIx).length() == 0) && (formParamValues.get(passwordParamIx) == null || formParamValues.get(passwordParamIx).length() == 0)) { URL url = new URL(address); HTTPCredentialsProvider prov = (HTTPCredentialsProvider) httpClient.getCredentialsProvider(); // don't allow empty username while (creds == null || creds.getUserPrincipal() == null || StringUtils.isNullOrEmpty(creds.getUserPrincipal().getName())) { creds = prov.getCredentials(new AuthScope(url.getHost(), url.getPort())); // it was user canceled lets stop processing if (creds == null && !prov.retry()) { return null; } } } // construct the name value pairs we will be sending List<NameValuePair> parameters = new ArrayList<NameValuePair>(); // there can be no params if (formParamNames != null) { for (int i = 0; i < formParamNames.size(); i++) { // we are on the username index, insert retrieved username value if (i == usernameParamIx && creds != null) { parameters .add(new BasicNameValuePair(formParamNames.get(i), creds.getUserPrincipal().getName())); } // we are on the password index, insert retrieved password val else if (i == passwordParamIx && creds != null) { parameters.add(new BasicNameValuePair(formParamNames.get(i), creds.getPassword())); } else // common name value pair, all info is present { parameters.add(new BasicNameValuePair(formParamNames.get(i), formParamValues.get(i))); } } } // our custom strategy, will check redirect handler should we redirect // if missing will use the default handler httpClient.setRedirectStrategy(new CustomRedirectStrategy(redirectHandler, parameters)); // Uses String UTF-8 to keep compatible with android version and // older versions of the http client libs, as the one used // in debian (4.1.x) String s = URLEncodedUtils.format(parameters, "UTF-8"); StringEntity entity = new StringEntity(s, "UTF-8"); // set content type to "application/x-www-form-urlencoded" entity.setContentType(URLEncodedUtils.CONTENT_TYPE); // insert post values encoded. postMethod.setEntity(entity); if (headerParamNames != null) { for (int i = 0; i < headerParamNames.size(); i++) { postMethod.addHeader(headerParamNames.get(i), headerParamValues.get(i)); } } // execute post return executeMethod(httpClient, postMethod, redirectHandler, parameters); }
From source file:com.naryx.tagfusion.cfm.xml.ws.javaplatform.DynamicWebServiceStubGenerator.java
@SuppressWarnings("deprecation") private String getWSDLContents(String wsdlURL, CallParameters cp) throws cfmRunTimeException { try {//from w w w. ja va 2s .co m String wsdlL = wsdlURL.toLowerCase(); String contents = null; if (wsdlL.startsWith("<?xml version")) { // The location is the WSDL itself (unexpected) contents = wsdlURL; } else { InputStream is = null; InputStreamReader isr = null; StringBuilder buffy = null; HttpGet method = null; try { if (wsdlL.startsWith("http:") || wsdlL.startsWith("https:")) { // Read from network DefaultHttpClient client = new DefaultHttpClient(); // Set the timeout int timeout = cp.getTimeout(); client.getParams().setParameter("http.connection.timeout", timeout); client.getParams().setParameter("http.socket.timeout", timeout); if (cp.getUsername() != null || cp.getPassword() != null) { // Set any credentials client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(cp.getUsername(), cp.getPassword())); } if (cp.getProxyServer() != null) { // Set the proxy HttpHost proxy = new HttpHost(cp.getProxyServer(), (cp.getProxyPort() == -1) ? cp.getDefaultProxyPort() : cp.getProxyPort()); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); if (cp.getProxyUser() != null || cp.getProxyPassword() != null) { // Set the proxy credentials client.getCredentialsProvider().setCredentials( new AuthScope(cp.getProxyServer(), cp.getProxyPort()), new UsernamePasswordCredentials(cp.getProxyUser(), cp.getProxyPassword())); } } // Create the method and get the response method = new HttpGet(wsdlURL); client.getParams().setParameter("http.protocol.handle-redirects", true); HttpResponse response = client.execute(method); switch (response.getStatusLine().getStatusCode()) { case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED: throw new cfmRunTimeException( catchDataFactory.extendedException("errorCode.runtimeError", "Failed to access WSDL: " + wsdlURL + ". Proxy authentication is required.", response.getStatusLine().toString())); case HttpStatus.SC_UNAUTHORIZED: throw new cfmRunTimeException( catchDataFactory.extendedException("errorCode.runtimeError", "Failed to access WSDL: " + wsdlURL + ". Authentication is required.", response.getStatusLine().toString())); case HttpStatus.SC_USE_PROXY: throw new cfmRunTimeException( catchDataFactory.extendedException("errorCode.runtimeError", "Failed to access WSDL: " + wsdlURL + ". The use of a proxy is required.", response.getStatusLine().toString())); } if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) throw new cfmRunTimeException(catchDataFactory.extendedException( "errorCode.runtimeError", "Failed to access WSDL: " + wsdlURL, response.getStatusLine().toString())); is = response.getEntity().getContent(); } else { // Just try to read off disk File f = new File(wsdlURL); is = new FileInputStream(f); } // Read the data char[] buf = new char[4096]; int read = -1; buffy = new StringBuilder(); isr = new InputStreamReader(is); while ((read = isr.read(buf, 0, buf.length)) != -1) buffy.append(buf, 0, read); contents = buffy.toString(); } finally { if (isr != null) isr.close(); if (is != null) is.close(); if (method != null) method.releaseConnection(); } } // Calc the sum and return return contents; } catch (IOException ex) { throw new cfmRunTimeException( catchDataFactory.generalException("errorCode.runtimeError", "Failed to access WSDL located at " + wsdlURL + ". There may be an error in the target WSDL. " + ex.getMessage())); } }
From source file:org.ocsinventoryng.android.actions.OCSProtocol.java
public String sendmethod(File pFile, String server, boolean gziped) throws OCSProtocolException { OCSLog ocslog = OCSLog.getInstance(); OCSSettings ocssettings = OCSSettings.getInstance(); ocslog.debug("Start send method"); String retour;/* w ww. j av a 2 s. c o m*/ HttpPost httppost; try { httppost = new HttpPost(server); } catch (IllegalArgumentException e) { ocslog.error(e.getMessage()); throw new OCSProtocolException("Incorect serveur URL"); } File fileToPost; if (gziped) { ocslog.debug("Start compression"); fileToPost = ocsfile.getGzipedFile(pFile); if (fileToPost == null) { throw new OCSProtocolException("Error during temp file creation"); } ocslog.debug("Compression done"); } else { fileToPost = pFile; } FileEntity fileEntity = new FileEntity(fileToPost, "text/plain; charset=\"UTF-8\""); httppost.setEntity(fileEntity); httppost.setHeader("User-Agent", http_agent); if (gziped) { httppost.setHeader("Content-Encoding", "gzip"); } DefaultHttpClient httpClient = getNewHttpClient(OCSSettings.getInstance().isSSLStrict()); if (ocssettings.isProxy()) { ocslog.debug("Use proxy : " + ocssettings.getProxyAdr()); HttpHost proxy = new HttpHost(ocssettings.getProxyAdr(), ocssettings.getProxyPort()); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } if (ocssettings.isAuth()) { ocslog.debug("Use AUTH : " + ocssettings.getLogin() + "/*****"); UsernamePasswordCredentials creds = new UsernamePasswordCredentials(ocssettings.getLogin(), ocssettings.getPasswd()); ocslog.debug(creds.toString()); httpClient.getCredentialsProvider() .setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds); } ocslog.debug("Call : " + server); HttpResponse localHttpResponse; try { localHttpResponse = httpClient.execute(httppost); ocslog.debug("Message sent"); } catch (ClientProtocolException e) { ocslog.error("ClientProtocolException" + e.getMessage()); throw new OCSProtocolException(e.getMessage()); } catch (IOException e) { String msg = appCtx.getString(R.string.err_cant_connect) + " " + e.getMessage(); ocslog.error(msg); throw new OCSProtocolException(msg); } try { int httpCode = localHttpResponse.getStatusLine().getStatusCode(); ocslog.debug("Response status code : " + String.valueOf(httpCode)); if (httpCode == 200) { if (gziped) { InputStream is = localHttpResponse.getEntity().getContent(); GZIPInputStream gzis = new GZIPInputStream(is); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buff = new byte[128]; int n; while ((n = gzis.read(buff, 0, buff.length)) > 0) { baos.write(buff, 0, n); } retour = baos.toString(); } else { retour = EntityUtils.toString(localHttpResponse.getEntity()); } } else if (httpCode == 400) { throw new OCSProtocolException("Error http 400 may be wrong agent version"); } else { ocslog.error("***Server communication error: "); throw new OCSProtocolException("Http communication error code " + String.valueOf(httpCode)); } ocslog.debug("Finnish send method"); } catch (IOException localIOException) { String msg = localIOException.getMessage(); ocslog.error(msg); throw new OCSProtocolException(msg); } return retour; }
From source file:org.opencastproject.remotetest.server.DigestAuthenticationTest.java
@Test public void testDigestAuthenticatedPost() throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); // Perform a HEAD, and extract the realm and nonce HttpHead head = new HttpHead(BASE_URL); head.addHeader("X-Requested-Auth", "Digest"); HttpResponse headResponse = httpclient.execute(head); Header authHeader = headResponse.getHeaders("WWW-Authenticate")[0]; String nonce = null;// w w w. j av a 2 s . c o m String realm = null; for (HeaderElement element : authHeader.getElements()) { if ("nonce".equals(element.getName())) { nonce = element.getValue(); } else if ("Digest realm".equals(element.getName())) { realm = element.getValue(); } } // Build the post UsernamePasswordCredentials creds = new UsernamePasswordCredentials("matterhorn_system_account", "CHANGE_ME"); HttpPost post = new HttpPost(BASE_URL + "/capture-admin/agents/testagent"); post.addHeader("X-Requested-Auth", "Digest"); httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds); List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(); params.add(new BasicNameValuePair("state", "idle")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8"); post.setEntity(entity); // Add the previously obtained nonce HttpContext localContext = new BasicHttpContext(); DigestScheme digestAuth = new DigestScheme(); digestAuth.overrideParamter("realm", realm); digestAuth.overrideParamter("nonce", nonce); localContext.setAttribute("preemptive-auth", digestAuth); // Send the POST try { HttpResponse response = httpclient.execute(post, localContext); String content = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals("testagent set to idle", content); } finally { httpclient.getConnectionManager().shutdown(); } }
From source file:edu.washington.shibboleth.attribute.resolver.provider.dataConnector.RwsDataConnector.java
/** * This queries the WS./* www. ja v a 2 s . c o m*/ * * @param queryString <code>String</code> the queryString that produced the attributes * @return <code>List</code> of results * @throws AttributeResolutionException if an error occurs performing the search */ protected Map<String, BaseAttribute> getRwsAttributes(String queryString) throws AttributeResolutionException { try { HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, searchTimeLimit); HttpConnectionParams.setSoTimeout(httpParams, searchTimeLimit); DefaultHttpClient httpClient = new DefaultHttpClient((ClientConnectionManager) connectionManager, httpParams); if (authenticationType == AUTHENTICATION_TYPE.BASIC) { httpClient.getCredentialsProvider().setCredentials(new AuthScope(baseURL.getHost(), basePort), new UsernamePasswordCredentials(username, password)); } HttpGet httpget = new HttpGet(baseUrl + queryString); HttpResponse response = httpClient.execute(httpget); HttpEntity entity = response.getEntity(); // null is error - should get something if (entity == null) { throw new AttributeResolutionException("httpclient get exception"); } // parse and return the response Document doc = documentBuilder.parse(entity.getContent()); Map<String, BaseAttribute> attributes = new HashMap<String, BaseAttribute>(); for (int i = 0; i < rwsAttributes.size(); i++) { RwsAttribute attr = rwsAttributes.get(i); Object result = attr.xpathExpression.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; log.debug("got {} matches to the xpath for {}", nodes.getLength(), attr.name); List<String> results = new Vector<String>(); if (nodes.getLength() == 0 && attr.noResultIsError) { log.error("got no attributes for {}, which required attriubtes", attr.name); throw new AttributeResolutionException("no attributes for " + attr.name); } for (int j = 0; j < nodes.getLength(); j++) { if (maxResults > 0 && maxResults < j) { log.error("too many results for {}", attr.name); break; } results.add((String) nodes.item(j).getTextContent()); } addBaseAttributes(attributes, attr.name, results); } return attributes; } catch (IOException e) { log.error("get rws io excpet: " + e); throw new AttributeResolutionException(); } catch (SAXException e) { log.error("get rws sax excpet: " + e); throw new AttributeResolutionException(); } catch (IllegalArgumentException e) { log.error("get rws arg excpet: " + e); throw new AttributeResolutionException(); } catch (XPathExpressionException e) { log.error("get rws arg excpet: " + e); throw new AttributeResolutionException(); } }
From source file:org.jboss.additional.testsuite.jdkall.past.eap_6_4_x.clustering.cluster.web.ClusteredWebSimpleTestCase.java
/** * Test if the authentication status is successfully propagated between cluster nodes. * * @param baseURL1/*from w ww. ja v a2s . c o m*/ * @param baseURL2 * @throws IOException when an HTTP client problem occurs */ @Test @InSequence(4) @OperateOnDeployment(DEPLOYMENT_1) public void testAuthnPropagation( @ArquillianResource(SimpleSecuredServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1, @ArquillianResource(SimpleSecuredServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2) throws IOException { DefaultHttpClient client = HttpClientUtils.relaxedCookieHttpClient(); final String servletPath = SimpleSecuredServlet.SERVLET_PATH.substring(1); // remove the leading slash try { // make request to a protected resource without authentication final HttpGet httpGet1 = new HttpGet(baseURL1.toString() + servletPath); HttpResponse response = client.execute(httpGet1); int statusCode = response.getStatusLine().getStatusCode(); assertEquals("Unexpected HTTP response status code.", HttpServletResponse.SC_UNAUTHORIZED, statusCode); EntityUtils.consume(response.getEntity()); // set credentials and retry the request final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user1", "password1"); client.getCredentialsProvider().setCredentials(new AuthScope(baseURL1.getHost(), baseURL1.getPort()), credentials); response = client.execute(httpGet1); statusCode = response.getStatusLine().getStatusCode(); assertEquals("Unexpected HTTP response status code.", HttpServletResponse.SC_OK, statusCode); EntityUtils.consume(response.getEntity()); waitForReplication(GRACE_TIME_TO_REPLICATE); // check on the 2nd server final HttpGet httpGet2 = new HttpGet(baseURL2.toString() + servletPath); response = client.execute(httpGet2); Assert.assertEquals("Unexpected HTTP response status code.", HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); EntityUtils.consume(response.getEntity()); } finally { client.getConnectionManager().shutdown(); } }
From source file:de.mendelson.comm.as2.send.MessageHttpUploader.java
/**Sets necessary HTTP authentication for this partner, depending on if it is an asny MDN that will be sent or an AS2 message. *If the partner is not configured to use HTTP authentication in any kind nothing will happen in here *///from ww w . j a va 2 s. c o m private void setHTTPAuthentication(DefaultHttpClient client, Partner receiver, boolean isMDN) { HTTPAuthentication authentication = null; if (isMDN) { authentication = receiver.getAuthenticationAsyncMDN(); } else { authentication = receiver.getAuthentication(); } if (authentication.isEnabled()) { Credentials userPassCredentials = new UsernamePasswordCredentials(authentication.getUser(), authentication.getPassword()); client.getCredentialsProvider().setCredentials(AuthScope.ANY, userPassCredentials); 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); } }