List of usage examples for org.apache.commons.httpclient HttpClient setState
public void setState(HttpState paramHttpState)
From source file:org.chiba.xml.xforms.connector.http.AbstractHTTPConnector.java
protected void execute(HttpMethod httpMethod) throws Exception { // (new HttpClient()).executeMethod(httpMethod); HttpClient client = new HttpClient(); if (submissionMap != null) { String sessionid = submissionMap.get(ChibaAdapter.SESSION_ID).toString(); if (sessionid != null) { HttpState state = client.getState(); state.setCookiePolicy(CookiePolicy.COMPATIBILITY); state.addCookie(new Cookie(httpMethod.getURI().getHost(), "JSESSIONID", sessionid, httpMethod.getPath(), null, false)); client.setState(state); }/*from w w w . ja v a2 s . c o m*/ } client.executeMethod(httpMethod); if (httpMethod.getStatusCode() >= 300) { throw new XFormsException( "HTTP status " + httpMethod.getStatusCode() + ": " + httpMethod.getStatusText()); } this.handleHttpMethod(httpMethod); }
From source file:org.codebistro.jsonrpc.TestClient.java
/** * JSON-RPC tests need this setup to operate propely. * This call invokes registerObject("test", ...) from the JSP *//*ww w .j av a2 s. co m*/ void setupServerTestEnvironment(String url) throws HttpException, IOException { HttpClient client = new HttpClient(); state = new HttpState(); client.setState(state); GetMethod method = new GetMethod(url); int status = client.executeMethod(method); if (status != HttpStatus.SC_OK) throw new RuntimeException( "Setup did not succeed. Make sure the JSON-RPC-Java test application is running on " + rootURL); }
From source file:org.eclipse.buckminster.p2.remote.client.RemoteRepositoryFactory.java
public static IRepositoryServer connect(URI location) throws ProvisionException { synchronized (s_servers) { IRepositoryServer server = s_servers.get(location); if (server != null) return server; HttpClient client = new HttpClient(); HttpState httpState = new HttpState(); client.setState(httpState); GetMethod method = null;// w w w . j av a 2 s . co m String locationStr = location.toString(); try { method = new GetMethod(locationStr); int status = client.executeMethod(method); if (status != HttpStatus.SC_OK) throw new IOException("Setup did not succeed"); HTTPSession session = (HTTPSession) Activator.getRegistry().createSession(location.toString()); session.setState(httpState); Client jsonClient = Client.create(session); server = (IRepositoryServer) jsonClient.openProxy(IRepositoryServer.SERVICE_NAME, IRepositoryServer.class); s_servers.put(location, server); return server; } catch (Exception e) { throw new ProvisionException(BuckminsterException.createStatus(e)); } finally { if (method != null) method.releaseConnection(); } } }
From source file:org.eclipse.mylyn.internal.provisional.commons.soap.CommonsHttpSender.java
/** * invoke creates a socket connection, sends the request SOAP message and then reads the response SOAP message back * from the SOAP server/* w w w. j a v a 2 s . c o m*/ * * @param msgContext * the messsage context * @throws AxisFault */ public void invoke(MessageContext msgContext) throws AxisFault { HttpMethodBase method = null; // if (log.isDebugEnabled()) { // log.debug(Messages.getMessage("enter00", "CommonsHTTPSender::invoke")); // } try { URL targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL)); // no need to retain these, as the cookies/credentials are // stored in the message context across multiple requests. // the underlying connection manager, however, is retained // so sockets get recycled when possible. HttpClient httpClient = new HttpClient(this.connectionManager); // the timeout value for allocation of connections from the pool httpClient.getParams().setConnectionManagerTimeout(this.clientProperties.getConnectionPoolTimeout()); HostConfiguration hostConfiguration = getHostConfiguration(httpClient, msgContext, targetURL); boolean posting = true; // If we're SOAP 1.2, allow the web method to be set from the // MessageContext. if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD); if (webMethod != null) { posting = webMethod.equals(HTTPConstants.HEADER_POST); } } if (posting) { Message reqMessage = msgContext.getRequestMessage(); method = new PostMethod(targetURL.toString()); // set false as default, addContetInfo can overwrite method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false); addContextInfo(method, httpClient, msgContext, targetURL); MessageRequestEntity requestEntity = null; if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) { requestEntity = new GzipMessageRequestEntity(method, reqMessage, httpChunkStream); } else { requestEntity = new MessageRequestEntity(method, reqMessage, httpChunkStream); } ((PostMethod) method).setRequestEntity(requestEntity); } else { method = new GetMethod(targetURL.toString()); addContextInfo(method, httpClient, msgContext, targetURL); } String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION); if (httpVersion != null) { if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10)) { method.getParams().setVersion(HttpVersion.HTTP_1_0); } // assume 1.1 } // don't forget the cookies! // Cookies need to be set on HttpState, since HttpMethodBase // overwrites the cookies from HttpState if (msgContext.getMaintainSession()) { HttpState state = httpClient.getState(); method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); String host = hostConfiguration.getHost(); String path = targetURL.getPath(); boolean secure = hostConfiguration.getProtocol().isSecure(); fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE, host, path, secure); fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE2, host, path, secure); httpClient.setState(state); } int returnCode = httpClient.executeMethod(hostConfiguration, method, null); String contentType = getHeader(method, HTTPConstants.HEADER_CONTENT_TYPE); String contentLocation = getHeader(method, HTTPConstants.HEADER_CONTENT_LOCATION); // String contentLength = getHeader(method, HTTPConstants.HEADER_CONTENT_LENGTH); if ((returnCode > 199) && (returnCode < 300)) { // SOAP return is OK - so fall through } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { // For now, if we're SOAP 1.2, fall through, since the range of // valid result codes is much greater } else if ((contentType != null) && !contentType.equals("text/html") //$NON-NLS-1$ && ((returnCode > 499) && (returnCode < 600))) { // SOAP Fault should be in here - so fall through } else { // String statusMessage = method.getStatusText(); // AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ try { // fault.setFaultDetailString(Messages.getMessage("return01", "" + returnCode, //$NON-NLS-1$ //$NON-NLS-2$ // method.getResponseBodyAsString())); // fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode)); // throw fault; throw AxisHttpFault.makeFault(method); } finally { method.releaseConnection(); // release connection back to pool. } } // wrap the response body stream so that close() also releases // the connection back to the pool. InputStream releaseConnectionOnCloseStream = createConnectionReleasingInputStream(method); Header contentEncoding = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING); if (contentEncoding != null) { if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP)) { releaseConnectionOnCloseStream = new GZIPInputStream(releaseConnectionOnCloseStream); } else if (contentEncoding.getValue().equals("") //$NON-NLS-1$ && msgContext.isPropertyTrue(SoapHttpSender.ALLOW_EMPTY_CONTENT_ENCODING)) { // assume no encoding } else { AxisFault fault = new AxisFault("HTTP", "unsupported content-encoding of '" //$NON-NLS-1$ //$NON-NLS-2$ + contentEncoding.getValue() + "' found", null, null); //$NON-NLS-1$ throw fault; } } Message outMsg = new Message(releaseConnectionOnCloseStream, false, contentType, contentLocation); // Transfer HTTP headers of HTTP message to MIME headers of SOAP message Header[] responseHeaders = method.getResponseHeaders(); MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders(); for (Header responseHeader : responseHeaders) { responseMimeHeaders.addHeader(responseHeader.getName(), responseHeader.getValue()); } outMsg.setMessageType(Message.RESPONSE); msgContext.setResponseMessage(outMsg); // if (log.isDebugEnabled()) { // if (null == contentLength) { // log.debug("\n" + Messages.getMessage("no00", "Content-Length")); // } // log.debug("\n" + Messages.getMessage("xmlRecd00")); // log.debug("-----------------------------------------------"); // log.debug(outMsg.getSOAPPartAsString()); // } // if we are maintaining session state, // handle cookies (if any) if (msgContext.getMaintainSession()) { Header[] headers = method.getResponseHeaders(); for (Header header : headers) { if (header.getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE)) { handleCookie(HTTPConstants.HEADER_COOKIE, header.getValue(), msgContext); } else if (header.getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE2)) { handleCookie(HTTPConstants.HEADER_COOKIE2, header.getValue(), msgContext); } } } // always release the connection back to the pool if // it was one way invocation if (msgContext.isPropertyTrue("axis.one.way")) { //$NON-NLS-1$ method.releaseConnection(); } } catch (Exception e) { // log.debug(e); throw AxisFault.makeFault(e); } // if (log.isDebugEnabled()) { // log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke")); // } }
From source file:org.exist.xquery.modules.httpclient.BaseHTTPClientFunction.java
/** * Performs a HTTP Request./* ww w. j av a 2 s.com*/ * * @param context The context of the calling XQuery * @param method The HTTP method for the request * @param persistState If true existing HTTP state (cookies, credentials, etc) are re-used and athe state is persisted for future HTTP Requests * @param parserFeatures Map of NekoHtml parser features to be used for the HTML parser. If null, the session-wide options will be used. * @param parserProperties Map of NekoHtml parser properties to be used for the HTML parser. If null, the session-wide options will be used. * * @return DOCUMENT ME! * * @throws IOException * @throws XPathException */ protected Sequence doRequest(final XQueryContext context, final HttpMethod method, boolean persistState, Map<String, Boolean> parserFeatures, Map<String, String> parserProperties) throws IOException, XPathException { Sequence encodedResponse = null; final HttpClient http = new HttpClient(); FeaturesAndProperties defaultFeaturesAndProperties = (FeaturesAndProperties) context .getXQueryContextVar(HTTP_MODULE_PERSISTENT_OPTIONS); if (defaultFeaturesAndProperties != null) { if (parserFeatures == null) parserFeatures = defaultFeaturesAndProperties.getFeatures(); if (parserProperties == null) parserProperties = defaultFeaturesAndProperties.getProperties(); } //execute the request try { //use existing state? if (persistState) { //get existing state final HttpState state = (HttpState) context.getXQueryContextVar(HTTP_MODULE_PERSISTENT_STATE); if (state != null) { http.setState(state); } } final String configFile = System.getProperty("http.configfile"); if (configFile != null) { final File f = new File(configFile); if (f.exists()) { setConfigFromFile(f, http); } else { logger.warn("http.configfile '" + f.getAbsolutePath() + "' does not exist!"); } } // Legacy: set the proxy server (if any) final String proxyHost = System.getProperty("http.proxyHost"); if (proxyHost != null) { //TODO: support for http.nonProxyHosts e.g. -Dhttp.nonProxyHosts="*.devonline.gov.uk|*.devon.gov.uk" final ProxyHost proxy = new ProxyHost(proxyHost, Integer.parseInt(System.getProperty("http.proxyPort"))); http.getHostConfiguration().setProxyHost(proxy); } //perform the request final int statusCode = http.executeMethod(method); encodedResponse = encodeResponseAsXML(context, method, statusCode, parserFeatures, parserProperties); //persist state? if (persistState) { context.setXQueryContextVar(HTTP_MODULE_PERSISTENT_STATE, http.getState()); } } catch (final Exception e) { LOG.error(e.getMessage(), e); encodedResponse = encodeErrorResponse(context, e.getMessage()); } return encodedResponse; }
From source file:org.jabsorb.client.ClientTestCase.java
/** * JSON-RPC tests need this setup to operate propely. This call invokes * registerObject("test", ...) from the JSP * /*from w w w . j a v a 2s . c o m*/ * @deprecated since we are running the server in-process */ void setupServerTestEnvironment(String url) throws HttpException, IOException { HttpClient client = new HttpClient(); state = new HttpState(); client.setState(state); GetMethod method = new GetMethod(url); int status = client.executeMethod(method); if (status != HttpStatus.SC_OK) throw new RuntimeException( "Setup did not succeed. Make sure the JSON-RPC-Java test application is running on " + getServiceRootURL()); }
From source file:org.jahia.services.notification.HttpClientService.java
private static HttpClient cloneHttpClient(HttpClient source) { HttpClient cloned = new HttpClient(source.getParams(), source.getHttpConnectionManager()); String sourceProxyHost = source.getHostConfiguration().getProxyHost(); if (sourceProxyHost != null) { cloned.getHostConfiguration().setProxy(sourceProxyHost, source.getHostConfiguration().getProxyPort()); }// w w w .j a va2 s . c o m Credentials proxyCredentials = source.getState().getProxyCredentials(AuthScope.ANY); if (proxyCredentials != null) { HttpState state = new HttpState(); state.setProxyCredentials(AuthScope.ANY, proxyCredentials); cloned.setState(state); } return cloned; }
From source file:org.jivesoftware.community.http.impl.HttpClientManagerImpl.java
public HttpClient getClient(URL url, com.sun.syndication.fetcher.impl.HttpClientFeedFetcher.CredentialSupplier credentialSupplier, int timeout) { HttpClient client = new HttpClient(); HttpConnectionManager conManager = client.getHttpConnectionManager(); if (JiveGlobals.getProperty("http.proxyHost") != null && JiveGlobals.getProperty("http.proxyPort") != null) { client.getHostConfiguration().setProxy(JiveGlobals.getProperty("http.proxyHost"), Integer.parseInt(JiveGlobals.getProperty("http.proxyPort"))); if (JiveGlobals.getProperty("http.proxyUsername") != null && JiveGlobals.getProperty("http.proxyPassword") != null) { HttpState state = new HttpState(); state.setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(JiveGlobals.getProperty("http.proxyUserName"), JiveGlobals.getProperty("http.proxyPassword"))); client.setState(state); }/*from w w w. j a v a2 s . c om*/ } if (timeout > 0) { conManager.getParams().setParameter("http.connection.timeout", Integer.valueOf(timeout)); conManager.getParams().setParameter("http.socket.timeout", Integer.valueOf(timeout)); } if (isHTTPS(url)) { int port = url.getPort() <= -1 ? 443 : url.getPort(); Protocol myhttps = new Protocol("https", new DummySSLSocketFactory(), port); Protocol.registerProtocol("https", myhttps); client.getHostConfiguration().setHost(url.getHost(), port, myhttps); } else { int port = url.getPort() <= -1 ? 80 : url.getPort(); client.getHostConfiguration().setHost(url.getHost(), port); } if (url.getUserInfo() != null && credentialSupplier == null) credentialSupplier = new BasicAuthCredentials(url.getUserInfo()); if (credentialSupplier != null) { client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials(new AuthScope(url.getHost(), -1, AuthScope.ANY_REALM), credentialSupplier.getCredentials(null, url.getHost())); } return client; }
From source file:org.mule.module.activiti.ActivitiConnector.java
protected HttpClient getClient() { HttpClient client = new HttpClient(); client.setState(new HttpState()); client.setHttpConnectionManager(this.clientConnectionManager); return client; }
From source file:org.mule.module.activiti.ActivitiRemoteConnector.java
public HttpClient createClient() { HttpClient client = new HttpClient(); client.setState(new HttpState()); client.setHttpConnectionManager(this.clientConnectionManager); return client; }