List of usage examples for org.apache.commons.httpclient HttpClient getState
public HttpState getState()
From source file:de.thorstenberger.examServer.ws.remoteusermanager.HTTPAuthAuthenticationProvider.java
private boolean authenticateUser(final URL url, final String login, final String pwd) throws IOException { final HttpClient client = new HttpClient(); client.getParams().setCookiePolicy(CookiePolicy.RFC_2109); client.getState().setCredentials(new AuthScope(url.getHost(), AuthScope.ANY_PORT, AuthScope.ANY_REALM), new UsernamePasswordCredentials(login, pwd)); final GetMethod authget = new GetMethod(url.toString()); authget.setDoAuthentication(true);//from w ww .j av a2 s .co m try { final int status = client.executeMethod(authget); // check if successful return status == 200; } finally { // release any connection resources used by the method authget.releaseConnection(); } }
From source file:com.twinsoft.convertigo.engine.util.WsReference.java
private static void tryAuthentication(RemoteFileReference wsReference) throws Exception { URL urlToConnect = wsReference.getUrl(); String wsdlUrl = wsReference.getUrlpath(); String username = wsReference.getAuthUser(); String password = wsReference.getAuthPassword(); HttpClient client = new HttpClient(); client.getState().setCredentials(new AuthScope(urlToConnect.getHost(), urlToConnect.getPort()), new UsernamePasswordCredentials(username, password)); GetMethod get = new GetMethod(wsdlUrl); get.setDoAuthentication(true);/* www . j av a 2 s . c o m*/ int statuscode = client.executeMethod(get); if (statuscode == HttpStatus.SC_UNAUTHORIZED) { throw new Exception(HttpStatus.SC_UNAUTHORIZED + " - Unauthorized connection!"); } }
From source file:io.hawt.web.JBossPostApp.java
@Test public void testPostWithCredentials() throws Exception { System.out.println("Using URL: " + url + " user: " + userName + " password: " + password); HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); //client.getParams().setAuthenticationPreemptive(true); method.setDoAuthentication(true);//from ww w .j av a 2 s .co m Credentials defaultcreds = new UsernamePasswordCredentials(userName, password); client.getState().setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM), defaultcreds); //client.getState().setProxyCredentials(new AuthScope(host, port, AuthScope.ANY_REALM), defaultcreds); method.setRequestEntity(new StringRequestEntity(data, "application/json", "UTF-8")); int result = client.executeMethod(method); System.out.println("Status: " + result); String response = method.getResponseBodyAsString(); System.out.println(response); }
From source file:com.zimbra.cs.httpclient.HttpProxyUtil.java
public static synchronized void configureProxy(HttpClient client) { try {//from ww w . j a v a 2 s. c om String url = Provisioning.getInstance().getLocalServer().getAttr(Provisioning.A_zimbraHttpProxyURL, null); if (url == null) return; // need to initializae all the statics if (sProxyUrl == null || !sProxyUrl.equals(url)) { sProxyUrl = url; sProxyUri = new URI(url); sProxyAuthScope = null; sProxyCreds = null; String userInfo = sProxyUri.getUserInfo(); if (userInfo != null) { int i = userInfo.indexOf(':'); if (i != -1) { sProxyAuthScope = new AuthScope(sProxyUri.getHost(), sProxyUri.getPort(), null); sProxyCreds = new UsernamePasswordCredentials(userInfo.substring(0, i), userInfo.substring(i + 1)); } } } if (ZimbraLog.misc.isDebugEnabled()) { ZimbraLog.misc.debug("setting proxy: " + url); } client.getHostConfiguration().setProxy(sProxyUri.getHost(), sProxyUri.getPort()); if (sProxyAuthScope != null && sProxyCreds != null) client.getState().setProxyCredentials(sProxyAuthScope, sProxyCreds); } catch (ServiceException e) { ZimbraLog.misc.warn("Unable to configureProxy: " + e.getMessage(), e); } catch (URISyntaxException e) { ZimbraLog.misc.warn("Unable to configureProxy: " + e.getMessage(), e); } }
From source file:com.gs.jrpip.client.ThankYouWriter.java
void sendThankYouRequest(CoalesceThankYouNotesKey key) { boolean success = false; List requestList = this.removeRequestList(key); if (done || requestList == null) { return;/* www .j a va 2s. co m*/ } HttpMethod streamedPostMethod = null; try { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Sending thank you for {}", requestList.size()); } AuthenticatedUrl url = key.getAuthenticatedUrl(); HttpClient httpClient = FastServletProxyFactory.getHttpClient(url); httpClient.getState().addCookies(key.getCookies()); OutputStreamWriter writer = new ThankYouStreamWriter(requestList); streamedPostMethod = FastServletProxyFactory.serverSupportsChunking(url) ? new StreamedPostMethod(url.getPath() + "?thanks", writer) : new BufferedPostMethod(url.getPath() + "?thanks", writer); httpClient.executeMethod(streamedPostMethod); int code = streamedPostMethod.getStatusCode(); streamedPostMethod.getResponseBodyAsStream().close(); streamedPostMethod.releaseConnection(); streamedPostMethod = null; success = code == 200; } catch (Exception e) { LOGGER.warn("Exception in JRPIP thank you note for URL: {} Retrying.", key.toString(), e); } finally { if (streamedPostMethod != null) { streamedPostMethod.releaseConnection(); } } if (!success) { this.readList(key, requestList); } }
From source file:com.pureinfo.force.net.impl.HttpUtilImpl.java
/** * @see com.pureinfo.force.net.IHttpUtil#getContent(String, NameValuePair[], * String, String)/* w w w . ja v a 2s . co m*/ */ public String getContent(String _sUrl, NameValuePair[] _args, String _sRequestCharset, String _sResponseCharset) throws IOTransferException { if (_sRequestCharset == null) { _sRequestCharset = "utf-8"; } //1. to create http client and set proxy HttpClient client = new HttpClient(); if (m_proxyHost != null) { client.getHostConfiguration().setProxyHost(m_proxyHost); if (m_sProxyUser != null & m_sProxyPassword != null) { client.getState().setProxyCredentials(// new AuthScope(m_proxyHost.getHostName(), m_proxyHost.getPort()), new UsernamePasswordCredentials(m_sProxyUser, m_sProxyPassword)); } } //2. to create post PostMethod method = new PostMethod(_sUrl); if (m_nRetryCount > 0) { method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, // new DefaultHttpMethodRetryHandler(m_nRetryCount, false)); } method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=" + _sRequestCharset); for (int i = 0; _args != null && i < _args.length; i++) { method.addParameter(_args[i]); } //3. to send request and read response String sResponse; try { client.executeMethod(method); sResponse = method.getResponseBodyAsString(); if (!method.getRequestCharSet().equals(_sRequestCharset)) { sResponse = new String(sResponse.getBytes(), _sResponseCharset); } return sResponse; } catch (Exception ex) { throw new IOTransferException(_sUrl, ex); } finally { method.releaseConnection(); } }
From source file:edu.du.penrose.systems.fedora.client.Downloader.java
/** * Get data via HTTP as an InputStream, following redirects, and supplying * credentials if the host is the Fedora server. *///from ww w . j ava 2 s . c o m public InputStream get(String url) throws IOException { GetMethod get = null; boolean ok = false; try { m_cManager.getParams().setConnectionTimeout(20000); HttpClient client = new HttpClient(m_cManager); client.getState().setCredentials(m_authScope, m_creds); client.getParams().setAuthenticationPreemptive(true); // don't bother with challenges int redirectCount = 0; // how many redirects did we follow int resultCode = 300; // not really, but enter the loop that way Dimension d = null; while (resultCode > 299 && resultCode < 400 && redirectCount < 25) { get = new GetMethod(url); get.setDoAuthentication(true); get.setFollowRedirects(true); // if ( myAdministrator!=null) { // d=Administrator.PROGRESS.getSize(); // // if they're using Administrator, tell them we're downloading... // Administrator.PROGRESS.setString("Downloading " + url + " . . ."); // Administrator.PROGRESS.setValue(100); // Administrator.PROGRESS.paintImmediately(0, 0, (int) d.getWidth()-1, (int) d.getHeight()-1); // } resultCode = client.executeMethod(get); if (resultCode > 299 && resultCode < 400) { redirectCount++; url = get.getResponseHeader("Location").getValue(); } } if (resultCode != 200) { System.err.println(get.getResponseBodyAsString()); throw new IOException( "Server returned error: " + resultCode + " " + HttpStatus.getStatusText(resultCode)); } ok = true; if (myAdministrator != null) { // cache it to a file File tempFile = File.createTempFile("fedora-client-download-", null); tempFile.deleteOnExit(); HashMap PARMS = new HashMap(); PARMS.put("in", get.getResponseBodyAsStream()); PARMS.put("out", new FileOutputStream(tempFile)); // do the actual download in a safe thread SwingWorker worker = new SwingWorker(PARMS) { public Object construct() { try { StreamUtility.pipeStream((InputStream) parms.get("in"), (OutputStream) parms.get("out"), 8192); } catch (Exception e) { thrownException = e; } return ""; } }; worker.start(); // The following code will run in the (safe) // Swing event dispatcher thread. int ms = 200; while (!worker.done) { try { // Administrator.PROGRESS.setValue(ms); // Administrator.PROGRESS.paintImmediately(0, 0, (int) d.getWidth()-1, (int) d.getHeight()-1); Thread.sleep(100); ms = ms + 100; if (ms >= 2000) ms = 200; } catch (InterruptedException ie) { } } if (worker.thrownException != null) throw worker.thrownException; // Administrator.PROGRESS.setValue(2000); // Administrator.PROGRESS.paintImmediately(0, 0, (int) d.getWidth()-1, (int) d.getHeight()-1); try { Thread.sleep(100); } catch (InterruptedException ie) { } return new FileInputStream(tempFile); } return get.getResponseBodyAsStream(); } catch (Exception e) { throw new IOException(e.getMessage()); } finally { if (get != null && !ok) get.releaseConnection(); // if (Administrator.INSTANCE!=null) { // Administrator.PROGRESS.setValue(0); // Administrator.PROGRESS.setString(""); // } } }
From source file:com.inbravo.scribe.rest.service.crm.zd.auth.basic.ZDBasicAuthManager.java
@Override public final boolean login(final String userId, final String password, final String crmURL, final String crmProtocol, final String port) throws Exception { logger.debug("----Inside login userId: " + userId + " & password: " + password + " & crmURL: " + crmURL + " & crmProtocol: " + crmProtocol); /* Validate protocol */ if (crmProtocol == null || "".equalsIgnoreCase(crmProtocol)) { /* Send user error */ throw new ScribeException( ScribeResponseCodes._1003 + "Invalid protocol to communicate with ZD: " + crmProtocol); }/* ww w . j ava 2 s. c o m*/ /* Trick: Check all live users on CRM currently */ final GetMethod getMethod = new GetMethod(crmProtocol + "://" + crmURL + "/users/current.xml"); getMethod.addRequestHeader("Content-Type", "application/xml"); final HttpClient httpclient = new HttpClient(); /* Set credentials */ httpclient.getState().setCredentials(new AuthScope(crmURL, this.validateCrmPort(port)), new UsernamePasswordCredentials(userId, password)); try { int result = httpclient.executeMethod(getMethod); logger.debug("----Inside login response code: " + result + " & body: " + getMethod.getResponseBodyAsString()); /* Check for authentication */ if (result == HttpStatus.SC_UNAUTHORIZED) { return false; } else { return true; } } catch (final IOException exception) { throw new ScribeException( ScribeResponseCodes._1020 + "Communication error while communicating with Zendesk CRM", exception); } finally { /* Release connection socket */ if (getMethod != null) { getMethod.releaseConnection(); } } }
From source file:com.inbravo.scribe.rest.service.crm.zd.auth.basic.ZDBasicAuthManager.java
@Override public final String getSessionId(final String userId, final String password, final String crmURL, final String crmProtocol, final String port) throws Exception { logger.debug("----Inside login userId: " + userId + " & password: " + password + " & crmURL: " + crmURL + " & crmProtocol: " + crmProtocol + " & crmPort: " + port); /* Validate protocol */ if (crmProtocol == null || "".equalsIgnoreCase(crmProtocol)) { /* Send user error */ throw new ScribeException( ScribeResponseCodes._1003 + "Invalid protocol to communicate with ZD: " + crmProtocol); }//from w w w . j a va 2 s .c om /* Trick: Check all live users on CRM currently */ final GetMethod getMethod = new GetMethod(crmProtocol + "://" + crmURL + "/users/current.xml"); getMethod.addRequestHeader("Content-Type", "application/xml"); final HttpClient httpclient = new HttpClient(); /* Set credentials */ httpclient.getState().setCredentials(new AuthScope(crmURL, this.validateCrmPort(port)), new UsernamePasswordCredentials(userId, password)); try { int result = httpclient.executeMethod(getMethod); logger.debug("----Inside getSessionId response code: " + result + " & body: " + getMethod.getResponseBodyAsString()); /* Check for authentication */ if (result == HttpStatus.SC_UNAUTHORIZED) { logger.debug("----Inside getSessionId found unauthorized user"); throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zendesk CRM"); } else { final String sessionId = getMethod.getResponseHeader("Set-Cookie").getValue(); logger.debug("----Inside getSessionId sessionId: " + sessionId); return sessionId; } } catch (final IOException exception) { throw new ScribeException( ScribeResponseCodes._1020 + "Communication error while communicating with Zendesk CRM", exception); } finally { /* Release connection socket */ if (getMethod != null) { getMethod.releaseConnection(); } } }
From source file:eu.learnpad.core.rest.DefaultRestResource.java
public HttpClient getClient(String userName, String password) { HttpClient httpClient = new HttpClient(); httpClient.getParams().setAuthenticationPreemptive(true); Credentials credentials = new UsernamePasswordCredentials(userName, password); AuthScope authentication = new AuthScope(DefaultRestResource.HOSTNAME, DefaultRestResource.PORT, AuthScope.ANY_REALM);//from w w w . j a va2 s . c o m httpClient.getState().setCredentials(authentication, credentials); return httpClient; }