List of usage examples for org.apache.commons.httpclient HttpState setCookiePolicy
public void setCookiePolicy(int paramInt)
From source file:com.liferay.util.Http.java
public static byte[] URLtoByteArray(String location, Cookie[] cookies, boolean post) throws IOException { byte[] byteArray = null; HttpMethod method = null;/* w ww . j a v a 2 s . c om*/ try { HttpClient client = new HttpClient(new SimpleHttpConnectionManager()); if (location == null) { return byteArray; } else if (!location.startsWith(HTTP_WITH_SLASH) && !location.startsWith(HTTPS_WITH_SLASH)) { location = HTTP_WITH_SLASH + location; } HostConfiguration hostConfig = new HostConfiguration(); hostConfig.setHost(new URI(location)); if (Validator.isNotNull(PROXY_HOST) && PROXY_PORT > 0) { hostConfig.setProxy(PROXY_HOST, PROXY_PORT); } client.setHostConfiguration(hostConfig); client.setConnectionTimeout(5000); client.setTimeout(5000); if (cookies != null && cookies.length > 0) { HttpState state = new HttpState(); state.addCookies(cookies); state.setCookiePolicy(CookiePolicy.COMPATIBILITY); client.setState(state); } if (post) { method = new PostMethod(location); } else { method = new GetMethod(location); } method.setFollowRedirects(true); client.executeMethod(method); Header locationHeader = method.getResponseHeader("location"); if (locationHeader != null) { return URLtoByteArray(locationHeader.getValue(), cookies, post); } InputStream is = method.getResponseBodyAsStream(); if (is != null) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); byte[] bytes = new byte[512]; for (int i = is.read(bytes, 0, 512); i != -1; i = is.read(bytes, 0, 512)) { buffer.write(bytes, 0, i); } byteArray = buffer.toByteArray(); is.close(); buffer.close(); } return byteArray; } finally { try { if (method != null) { method.releaseConnection(); } } catch (Exception e) { Logger.error(Http.class, e.getMessage(), e); } } }
From source file:autohit.call.modules.SimpleHttpModule.java
/** * Start method for an HTTP session. It will set the target address for the client, as well as * clearing any state./*from ww w . ja v a 2 s .c om*/ * * @param addr * the address. Do not include protocol, but you may add port * (ie. "www.goatland.com:80"). * @throws CallException */ private void start(String addr, int port) throws CallException { try { httpClient = new HttpClient(new MultiThreadedHttpConnectionManager()); creds = null; HttpState initialState = new HttpState(); initialState.setCookiePolicy(CookiePolicy.COMPATIBILITY); httpClient.setState(initialState); httpClient.setConnectionTimeout(DEFAULT_TIMEOUT); httpClient.getHostConfiguration().setHost(addr, port, "http"); } catch (Exception ex) { throw new CallException( "Serious fault while creating session with start method. Session is not valid. error=" + ex.getMessage(), CallException.CODE_MODULE_FAULT, ex); } // NO CODE AFTER THIS! started = true; }
From source file:autohit.call.modules.SimpleHttpModule.java
/** * Start method for an HTTPS session. It will set the target address for the client, as well as * clearing any state.//from ww w. j a va 2 s . c om * * @param addr * the address. Do not include protocol, but you may add port * (ie. "www.goatland.com:443"). * @throws CallException */ private void starthttps(String addr, int port) throws CallException { try { // buidl protocol Protocol myhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), port); httpClient = new HttpClient(new MultiThreadedHttpConnectionManager()); creds = null; HttpState initialState = new HttpState(); initialState.setCookiePolicy(CookiePolicy.COMPATIBILITY); httpClient.setState(initialState); httpClient.setConnectionTimeout(DEFAULT_TIMEOUT); httpClient.getHostConfiguration().setHost(addr, port, myhttps); } catch (Exception ex) { throw new CallException( "Serious fault while creating session with start method. Session is not valid. error=" + ex.getMessage(), CallException.CODE_MODULE_FAULT, ex); } // NO CODE AFTER THIS! started = true; }
From source file:org.activebpel.rt.axis.bpel.handlers.AeHTTPSender.java
/** * invoke creates a socket connection, sends the request SOAP message and then * reads the response SOAP message back from the SOAP server * * @param msgContext the message context * * @throws AxisFault// w ww . j av a 2 s . c om * @deprecated */ public void invoke(MessageContext msgContext) throws AxisFault { HttpMethodBase method = null; if (log.isDebugEnabled()) { log.debug(Messages.getMessage("enter00", //$NON-NLS-1$ "CommonsHTTPSender::invoke")); //$NON-NLS-1$ } 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(connectionManager); // the timeout value for allocation of connections from the pool httpClient.setHttpConnectionFactoryTimeout(clientProperties.getConnectionPoolTimeout()); HostConfiguration hostConfiguration = getHostConfiguration(httpClient, targetURL); httpClient.setHostConfiguration(hostConfiguration); // look for option to send credentials preemptively (w/out challenge) // Control of Preemptive is controlled via policy on a per call basis. String preemptive = (String) msgContext.getProperty("HTTPPreemptive"); //$NON-NLS-1$ if ("true".equals(preemptive)) //$NON-NLS-1$ { httpClient.getParams().setAuthenticationPreemptive(true); } String webMethod = null; 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) { webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD); if (webMethod != null) { posting = webMethod.equals(HTTPConstants.HEADER_POST); } } Message reqMessage = msgContext.getRequestMessage(); if (posting) { method = new PostMethod(targetURL.toString()); addContextInfo(method, httpClient, msgContext, targetURL); ByteArrayOutputStream baos = new ByteArrayOutputStream(); reqMessage.writeTo(baos); ((PostMethod) method).setRequestBody(new ByteArrayInputStream(baos.toByteArray())); ((PostMethod) method).setUseExpectHeader(false); // workaround for } else { method = new GetMethod(targetURL.toString()); addContextInfo(method, httpClient, msgContext, targetURL); } // 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(); state.setCookiePolicy(CookiePolicy.COMPATIBILITY); String host = hostConfiguration.getHost(); String path = targetURL.getPath(); boolean secure = hostConfiguration.getProtocol().isSecure(); String ck1 = (String) msgContext.getProperty(HTTPConstants.HEADER_COOKIE); String ck2 = (String) msgContext.getProperty(HTTPConstants.HEADER_COOKIE2); if (ck1 != null) { int index = ck1.indexOf('='); state.addCookie(new Cookie(host, ck1.substring(0, index), ck1.substring(index + 1), path, null, secure)); } if (ck2 != null) { int index = ck2.indexOf('='); state.addCookie(new Cookie(host, ck2.substring(0, index), ck2.substring(index + 1), path, null, secure)); } httpClient.setState(state); } boolean hasSoapFault = false; int returnCode = httpClient.executeMethod(method); String contentType = null; String contentLocation = null; String contentLength = null; if (method.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE) != null) { contentType = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE).getValue(); } if (method.getResponseHeader(HTTPConstants.HEADER_CONTENT_LOCATION) != null) { contentLocation = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_LOCATION).getValue(); } if (method.getResponseHeader(HTTPConstants.HEADER_CONTENT_LENGTH) != null) { contentLength = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_LENGTH).getValue(); } contentType = (null == contentType) ? null : contentType.trim(); 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 hasSoapFault = true; } else { String statusMessage = method.getStatusText(); AxisFault fault = new AxisFault("HTTP", //$NON-NLS-1$ "(" + returnCode + ")" //$NON-NLS-1$ //$NON-NLS-2$ + statusMessage, null, null); try { fault.setFaultDetailString(Messages.getMessage("return01", //$NON-NLS-1$ "" + returnCode, method.getResponseBodyAsString())); //$NON-NLS-1$ fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode)); throw fault; } 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); 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 (int i = 0; i < responseHeaders.length; i++) { Header responseHeader = responseHeaders[i]; responseMimeHeaders.addHeader(responseHeader.getName(), responseHeader.getValue()); } OperationDesc operation = msgContext.getOperation(); if (hasSoapFault || operation.getMep().equals(OperationType.REQUEST_RESPONSE)) { msgContext.setResponseMessage(outMsg); } else { // Change #1 // // If the operation is a one-way, then don't set the response // on the msg context. Doing so will cause Axis to attempt to // read from a non-existent SOAP message which causes errors. // // Note: also checking to see if the return type is our "VOID" // QName from the AeInvokeHandler since that's our workaround // for avoiding Axis's Thread creation in Call.invokeOneWay() // // Since the message context won't have a chance to consume the // response stream (which closes the connection), close the // connection here. method.releaseConnection(); } if (log.isDebugEnabled()) { if (null == contentLength) { log.debug("\n" //$NON-NLS-1$ + Messages.getMessage("no00", "Content-Length")); //$NON-NLS-1$ //$NON-NLS-2$ } log.debug("\n" + Messages.getMessage("xmlRecd00")); //$NON-NLS-1$ //$NON-NLS-2$ log.debug("-----------------------------------------------"); //$NON-NLS-1$ log.debug(outMsg.getSOAPPartAsString()); } // if we are maintaining session state, // handle cookies (if any) if (msgContext.getMaintainSession()) { Header[] headers = method.getResponseHeaders(); for (int i = 0; i < headers.length; i++) { if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE)) msgContext.setProperty(HTTPConstants.HEADER_COOKIE, cleanupCookie(headers[i].getValue())); else if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE2)) msgContext.setProperty(HTTPConstants.HEADER_COOKIE2, cleanupCookie(headers[i].getValue())); } } } catch (Throwable t) { log.debug(t); if (method != null) { method.releaseConnection(); } // We can call Axis.makeFault() if it's an exception; otherwise // construct the AxisFault directly. throw (t instanceof Exception) ? AxisFault.makeFault((Exception) t) : new AxisFault(t.getLocalizedMessage(), t); } if (log.isDebugEnabled()) { log.debug(Messages.getMessage("exit00", //$NON-NLS-1$ "CommonsHTTPSender::invoke")); //$NON-NLS-1$ } }
From source file:org.apache.commons.httpclient.demo.CookiesTrial.java
@SuppressWarnings("deprecation") public static void main(String[] args) throws Exception { //A new cookie for the domain 127.0.0.1 //Cookie Name= ABCD Value=00000 Path=/ MaxAge=-1 Secure=False Cookie mycookie = new Cookie("90.0.12.20", "ABCD", "00000", "/", -1, false); //Create a new HttpState container HttpState initialState = new HttpState(); initialState.addCookie(mycookie);//from w w w . ja v a 2s .c o m //Set to COMPATIBILITY for it to work in as many cases as possible initialState.setCookiePolicy(CookiePolicy.COMPATIBILITY); //create new client HttpClient httpclient = new HttpClient(); //set the HttpState for the client httpclient.setState(initialState); GetMethod getMethod = new GetMethod(url); //Execute a GET method //int result = httpclient.executeMethod(getMethod); System.out.println("statusLine>>>" + getMethod.getStatusLine()); //Get cookies stored in the HttpState for this instance of HttpClient Cookie[] cookies = httpclient.getState().getCookies(); for (int i = 0; i < cookies.length; i++) { System.out.println("\nCookieName=" + cookies[i].getName()); System.out.println("Value=" + cookies[i].getValue()); System.out.println("Domain=" + cookies[i].getDomain()); } getMethod.releaseConnection(); }
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 ww w . jav a 2 s .c om*/ } } client.executeMethod(httpMethod); if (httpMethod.getStatusCode() >= 300) { throw new XFormsException( "HTTP status " + httpMethod.getStatusCode() + ": " + httpMethod.getStatusText()); } this.handleHttpMethod(httpMethod); }