List of usage examples for org.apache.commons.httpclient HttpClient getHostConfiguration
public HostConfiguration getHostConfiguration()
From source file:com.mrfeinberg.translation.AbstractTranslationService.java
public Runnable translate(final String phrase, final LanguagePair lp, final TranslationListener listener) { final Language b = lp.b(); final HttpClient httpClient = new HttpClient(); if (proxyPrefs.getUseProxy()) { httpClient.getHostConfiguration().setProxy(proxyPrefs.getProxyHost(), proxyPrefs.getProxyPort()); }/*from ww w. jav a 2 s . c om*/ final HttpMethod httpMethod = getHttpMethod(phrase, lp); final Callable<String> callable = new Callable<String>() { public String call() throws Exception { int result = httpClient.executeMethod(httpMethod); if (result != 200) { throw new Exception("Got " + result + " status for " + httpMethod.getURI()); } final BufferedReader in = new BufferedReader( new InputStreamReader(httpMethod.getResponseBodyAsStream(), "utf8")); try { final StringBuilder sb = new StringBuilder(); String line; while ((line = in.readLine()) != null) sb.append(line); return sb.toString(); } finally { in.close(); httpMethod.releaseConnection(); } } }; final FutureTask<String> tc = new FutureTask<String>(callable); return new Runnable() { public void run() { try { executor.execute(tc); final String result = tc.get(timeout, TimeUnit.MILLISECONDS); String found = findTranslatedText(result); if (found == null) { listener.error("Cannot find translated text in result."); } else { found = found.replaceAll("\\s+", " "); listener.result(found, b); } } catch (final TimeoutException e) { listener.timedOut(); } catch (final InterruptedException e) { listener.cancelled(); } catch (final Exception e) { e.printStackTrace(); listener.error(e.toString()); } } }; }
From source file:com.twinsoft.convertigo.engine.billing.GoogleAnalyticsTicketManager.java
private HttpClient prepareHttpClient(String[] url) throws EngineException, MalformedURLException { final Pattern scheme_host_pattern = Pattern.compile("https://(.*?)(?::([\\d]*))?(/.*|$)"); HttpClient client = new HttpClient(); HostConfiguration hostConfiguration = client.getHostConfiguration(); HttpState httpState = new HttpState(); client.setState(httpState);//from w w w. j av a 2s. co m if (proxyManager != null) { proxyManager.getEngineProperties(); proxyManager.setProxy(hostConfiguration, httpState, new URL(url[0])); } Matcher matcher = scheme_host_pattern.matcher(url[0]); if (matcher.matches()) { String host = matcher.group(1); String sPort = matcher.group(2); int port = 443; try { port = Integer.parseInt(sPort); } catch (Exception e) { } try { Protocol myhttps = new Protocol("https", MySSLSocketFactory.getSSLSocketFactory(null, null, null, null, true), port); hostConfiguration.setHost(host, port, myhttps); url[0] = matcher.group(3); } catch (Exception e) { e.printStackTrace(); e.printStackTrace(); } } return client; }
From source file:com.htmlhifive.tools.jslint.engine.download.AbstractDownloadEngineSupport.java
/** * ?url????eclipse?????HttpClient??.<br> * ??//from w w w . jav a 2 s .c o m * {@link AbstractDownloadEngineSupport#getConnectionTimeout()}.<br> * ? {@link AbstractDownloadEngineSupport#getRetryTimes()} * * @param url URL * @return HttpClient */ private HttpClient createHttpClient(String url) { ServiceTracker<IProxyService, IProxyService> proxyTracker = new ServiceTracker<IProxyService, IProxyService>( JSLintPlugin.getDefault().getBundle().getBundleContext(), IProxyService.class, null); boolean useProxy = false; String proxyHost = null; int proxyPort = 0; String userId = null; String password = null; try { proxyTracker.open(); IProxyService service = proxyTracker.getService(); IProxyData[] datas = service.select(new URI(url)); for (IProxyData proxyData : datas) { if (proxyData.getHost() != null) { useProxy = true; proxyHost = proxyData.getHost(); proxyPort = proxyData.getPort(); userId = proxyData.getUserId(); password = proxyData.getPassword(); } } } catch (URISyntaxException e) { throw new RuntimeException(Messages.EM0100.getText(), e); } finally { proxyTracker.close(); } HttpClient client = new HttpClient(); if (useProxy) { client.getHostConfiguration().setProxy(proxyHost, proxyPort); if (StringUtils.isNotEmpty(userId)) { // ????? client.getState().setProxyCredentials(new AuthScope(proxyHost, proxyPort, "realm"), new UsernamePasswordCredentials(userId, password)); } } client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(getRetryTimes(), true)); client.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, getConnectionTimeout()); return client; }
From source file:be.fedict.trust.ocsp.OnlineOcspRepository.java
private OCSPResp getOcspResponse(URI ocspUri, X509Certificate certificate, X509Certificate issuerCertificate) throws OCSPException, IOException { LOG.debug("OCSP URI: " + ocspUri); OCSPReqGenerator ocspReqGenerator = new OCSPReqGenerator(); CertificateID certId = new CertificateID(CertificateID.HASH_SHA1, issuerCertificate, certificate.getSerialNumber()); ocspReqGenerator.addRequest(certId); OCSPReq ocspReq = ocspReqGenerator.generate(); byte[] ocspReqData = ocspReq.getEncoded(); PostMethod postMethod = new PostMethod(ocspUri.toString()); RequestEntity requestEntity = new ByteArrayRequestEntity(ocspReqData, "application/ocsp-request"); postMethod.addRequestHeader("User-Agent", "jTrust OCSP Client"); postMethod.setRequestEntity(requestEntity); HttpClient httpClient = new HttpClient(); if (null != this.networkConfig) { httpClient.getHostConfiguration().setProxy(this.networkConfig.getProxyHost(), this.networkConfig.getProxyPort()); }/* ww w . java 2 s . com*/ if (null != this.credentials) { HttpState httpState = httpClient.getState(); this.credentials.init(httpState); } int responseCode; try { httpClient.executeMethod(postMethod); responseCode = postMethod.getStatusCode(); } catch (ConnectException e) { LOG.debug("OCSP responder is down"); return null; } if (HttpURLConnection.HTTP_OK != responseCode) { LOG.error("HTTP response code: " + responseCode); return null; } Header responseContentTypeHeader = postMethod.getResponseHeader("Content-Type"); if (null == responseContentTypeHeader) { LOG.debug("no Content-Type response header"); return null; } String resultContentType = responseContentTypeHeader.getValue(); if (!"application/ocsp-response".equals(resultContentType)) { LOG.debug("result content type not application/ocsp-response"); return null; } Header responseContentLengthHeader = postMethod.getResponseHeader("Content-Length"); if (null != responseContentLengthHeader) { String resultContentLength = responseContentLengthHeader.getValue(); if ("0".equals(resultContentLength)) { LOG.debug("no content returned"); return null; } } OCSPResp ocspResp = new OCSPResp(postMethod.getResponseBodyAsStream()); LOG.debug("OCSP response size: " + ocspResp.getEncoded().length + " bytes"); return ocspResp; }
From source file:jenkins.plugins.elanceodesk.workplace.notifier.HttpWorker.java
private HttpClient getHttpClient() { HttpClient client = new HttpClient(); if (Jenkins.getInstance() != null) { ProxyConfiguration proxy = Jenkins.getInstance().proxy; if (proxy != null) { client.getHostConfiguration().setProxy(proxy.name, proxy.port); String username = proxy.getUserName(); String password = proxy.getPassword(); // Consider it to be passed if username specified. Sufficient? if (username != null && !"".equals(username.trim())) { logger.println("Using proxy authentication (user=" + username + ")"); // http://hc.apache.org/httpclient-3.x/authentication.html#Proxy_Authentication // and // http://svn.apache.org/viewvc/httpcomponents/oac.hc3x/trunk/src/examples/BasicAuthenticationExample.java?view=markup client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); }/*w ww . j ava 2 s . c om*/ } } return client; }
From source file:net.sourceforge.jwbf.bots.HttpBot.java
/** * /*from w w w . ja va 2 s . co m*/ * @param client * if you whant to add some specials * @param u * like http://www.yourOwnWiki.org/w/index.php * */ protected final void setConnection(final HttpClient client, final URL u) { this.client = client; client.getParams().setParameter("http.useragent", "JWBF " + JWBF.getVersion()); client.getHostConfiguration().setHost(u.getHost(), u.getPort(), u.getProtocol()); cc = new HttpActionClient(client, u.getPath()); }
From source file:com.epam.wilma.gepard.testclient.MultiStubHttpPostRequestSender.java
/** * Sends a new HTTP request to a server through a proxy. Also logs request and response with gepard framework. * * @param tc the running test case * @param requestParameters a set of parameters that will set the content of the request * and specify the proxy it should go through * @return with Response Holder class.//ww w.jav a 2s.c om * @throws IOException in case error occurs * @throws ParserConfigurationException in case error occurs * @throws SAXException in case error occurs */ public ResponseHolder callWilmaTestServer(final WilmaTestCase tc, final MultiStubRequestParameters requestParameters) throws IOException, ParserConfigurationException, SAXException { String responseCode; ResponseHolder responseMessage; HttpClient httpClient = new HttpClient(); PostMethod httpPost = new PostMethod(requestParameters.getTestServerUrl()); if (requestParameters.isUseProxy()) { httpClient.getHostConfiguration().setProxy(requestParameters.getWilmaHost(), requestParameters.getWilmaPort()); } createRequest(requestParameters, httpPost); httpClient.getHttpConnectionManager().getParams().setSendBufferSize(Integer .valueOf(tc.getTestClassExecutionData().getEnvironment().getProperty("http.socket.sendbuffer"))); httpClient.getHttpConnectionManager().getParams().setReceiveBufferSize(Integer .valueOf(tc.getTestClassExecutionData().getEnvironment().getProperty("http.socket.receivebuffer"))); int statusCode; statusCode = httpClient.executeMethod(httpPost); responseCode = "status code: " + statusCode + "\n"; responseMessage = createResponse(httpPost); responseMessage.setResponseCode(responseCode); tc.setActualResponseCode(statusCode); Header contentTypeHeader = httpPost.getResponseHeader("Content-Type"); if (contentTypeHeader != null) { tc.setActualResponseContentType(contentTypeHeader.getValue()); } Header sequenceHeader = httpPost.getResponseHeader("Wilma-Sequence"); if (sequenceHeader != null) { tc.setActualDialogDescriptor(sequenceHeader.getValue()); } return responseMessage; }
From source file:ie.pars.nlp.sketchengine.interactions.SKEInteractionsBase.java
/** * Create a session id to communicate with the server * * @return// www .j a v a 2s.c o m */ protected HttpClient getSessionID() { String cookie_policy = CookiePolicy.DEFAULT; //use CookiePolicy.BROWSER_COMPATIBILITY in case cookie handling does not work HttpClient client = new HttpClient(); try { Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory) new EasySSLProtocolSocketFactory(), 443)); client.getHostConfiguration().setHost(rootURL, 80, "http"); client.getParams().setCookiePolicy(cookie_policy); } catch (java.security.GeneralSecurityException | IOException e) { e.printStackTrace(); } client.getParams().setCookiePolicy(cookie_policy); // retrieve session id GetMethod authget = new GetMethod("/login/"); try { int code = client.executeMethod(authget); } catch (IOException ex) { System.err.println("Error: couldn't retrieve session ID from Sketch Engine server."); System.exit(1); } authget.releaseConnection(); return client; }
From source file:icom.jpa.bdk.BdkUserContextImpl.java
BdkUserContextImpl(PersistenceContextImpl context, String host, int port, String protocol, String username, char[] password) throws Exception { HttpClient httpClient = new HttpClient(connectionManager); Credentials defaultCredentials = new UsernamePasswordCredentials(username, new String(password)); httpClient.getParams().setAuthenticationPreemptive(true); httpClient.getHostConfiguration().setHost(host, port, protocol); AuthScope authScope = new AuthScope(host, port, AuthScope.ANY_REALM); httpClient.getState().setCredentials(authScope, defaultCredentials); this.httpClient = httpClient; this.authUserName = username; OrganizationUser myUser = getMyUser(context); actorId = myUser.getCollabId().getId(); String enterpriseId = actorId.substring(0, 4); String siteId = actorId.substring(5, 9); BdkDataAccessUtilsImpl bdkDataAccessUtils = (BdkDataAccessUtilsImpl) context.getDataAccessUtils(); bdkDataAccessUtils.setEnterpriseId(enterpriseId); bdkDataAccessUtils.setSiteId(siteId); antiCSRF = getAntiCrossSiteRequestForgery(); }
From source file:com.epam.wilma.gepard.testclient.HttpGetRequestSender.java
/** * Sends a new HTTP request to a server through a proxy. Also logs request and response with gepard framework. * * @param tc is the caller Test Case./*from w w w . j a v a 2s .c o m*/ * @param requestParameters a set of parameters that will set the content of the request * and specify the proxy it should go through * @return with Response Holder class. * @throws IOException in case error occurs * @throws ParserConfigurationException in case error occurs * @throws SAXException in case error occurs */ public ResponseHolder callWilmaTestServer(final WilmaTestCase tc, final RequestParameters requestParameters) throws IOException, ParserConfigurationException, SAXException { String responseCode; ResponseHolder responseMessage; HttpClient httpClient = new HttpClient(); GetMethod httpGet = new GetMethod(requestParameters.getTestServerUrl()); if (requestParameters.isUseProxy()) { httpClient.getHostConfiguration().setProxy(requestParameters.getWilmaHost(), requestParameters.getWilmaPort()); } createRequest(requestParameters, httpGet); tc.logGetRequestEvent(requestParameters); //this dumps the request String sendBuffer; try { sendBuffer = tc.getTestClassExecutionData().getEnvironment().getProperty("http.socket.sendbuffer"); } catch (NullPointerException e) { sendBuffer = DEFAULT_BUFFER_SIZE_STRING; } String receiveBuffer; try { receiveBuffer = tc.getTestClassExecutionData().getEnvironment() .getProperty("http.socket.receivebuffer"); } catch (NullPointerException e) { receiveBuffer = DEFAULT_BUFFER_SIZE_STRING; } httpClient.getHttpConnectionManager().getParams().setSendBufferSize(Integer.valueOf(sendBuffer)); httpClient.getHttpConnectionManager().getParams().setReceiveBufferSize(Integer.valueOf(receiveBuffer)); int statusCode; statusCode = httpClient.executeMethod(httpGet); responseCode = "status code: " + statusCode + "\n"; responseMessage = createResponse(httpGet); responseMessage.setResponseCode(responseCode); tc.setActualResponseCode(statusCode); Header contentTypeHeader = httpGet.getResponseHeader("Content-Type"); if (contentTypeHeader != null) { tc.setActualResponseContentType(contentTypeHeader.getValue()); } Header sequenceHeader = httpGet.getResponseHeader("Wilma-Sequence"); if (sequenceHeader != null) { tc.setActualDialogDescriptor(sequenceHeader.getValue()); } tc.logResponseEvent(responseMessage); //this dumps the response return responseMessage; }