⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 commonshttpsender.java

📁 Java有关XML编程需要用到axis 的源代码 把里面bin下的包导入相应的Java工程 进行使用
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
/* * Copyright 2001-2004 The Apache Software Foundation. *  * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *  *      http://www.apache.org/licenses/LICENSE-2.0 *  * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.axis.transport.http;import org.apache.axis.AxisFault;import org.apache.axis.Constants;import org.apache.axis.Message;import org.apache.axis.MessageContext;import org.apache.axis.components.logger.LogFactory;import org.apache.axis.components.net.CommonsHTTPClientProperties;import org.apache.axis.components.net.CommonsHTTPClientPropertiesFactory;import org.apache.axis.components.net.TransportClientProperties;import org.apache.axis.components.net.TransportClientPropertiesFactory;import org.apache.axis.handlers.BasicHandler;import org.apache.axis.soap.SOAP12Constants;import org.apache.axis.soap.SOAPConstants;import org.apache.axis.utils.JavaUtils;import org.apache.axis.utils.Messages;import org.apache.axis.utils.NetworkUtils;import org.apache.commons.httpclient.Cookie;import org.apache.commons.httpclient.Credentials;import org.apache.commons.httpclient.Header;import org.apache.commons.httpclient.HostConfiguration;import org.apache.commons.httpclient.HttpClient;import org.apache.commons.httpclient.HttpConnectionManager;import org.apache.commons.httpclient.HttpMethodBase;import org.apache.commons.httpclient.HttpState;import org.apache.commons.httpclient.HttpVersion;import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;import org.apache.commons.httpclient.NTCredentials;import org.apache.commons.httpclient.UsernamePasswordCredentials;import org.apache.commons.httpclient.auth.AuthScope;import org.apache.commons.httpclient.cookie.CookiePolicy;import org.apache.commons.httpclient.methods.GetMethod;import org.apache.commons.httpclient.methods.PostMethod;import org.apache.commons.httpclient.methods.RequestEntity;import org.apache.commons.httpclient.params.HttpMethodParams;import org.apache.commons.logging.Log;import javax.xml.soap.MimeHeader;import javax.xml.soap.MimeHeaders;import javax.xml.soap.SOAPException;import java.io.ByteArrayOutputStream;import java.io.FilterInputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.URL;import java.util.ArrayList;import java.util.Hashtable;import java.util.Iterator;import java.util.Map;import java.util.StringTokenizer;import java.util.zip.GZIPInputStream;import java.util.zip.GZIPOutputStream;/** * This class uses Jakarta Commons's HttpClient to call a SOAP server. * * @author Davanum Srinivas (dims@yahoo.com) * History: By Chandra Talluri * Modifications done for maintaining sessions. Cookies needed to be set on * HttpState not on MessageContext, since ttpMethodBase overwrites the cookies  * from HttpState. Also we need to setCookiePolicy on HttpState to  * CookiePolicy.COMPATIBILITY else it is defaulting to RFC2109Spec and adding  * Version information to it and tomcat server not recognizing it */public class CommonsHTTPSender extends BasicHandler {        /** Field log           */    protected static Log log =        LogFactory.getLog(CommonsHTTPSender.class.getName());        protected HttpConnectionManager connectionManager;    protected CommonsHTTPClientProperties clientProperties;    boolean httpChunkStream = true; //Use HTTP chunking or not.    public CommonsHTTPSender() {        initialize();    }    protected void initialize() {        MultiThreadedHttpConnectionManager cm = new MultiThreadedHttpConnectionManager();        this.clientProperties = CommonsHTTPClientPropertiesFactory.create();        cm.getParams().setDefaultMaxConnectionsPerHost(clientProperties.getMaximumConnectionsPerHost());        cm.getParams().setMaxTotalConnections(clientProperties.getMaximumTotalConnections());        // If defined, set the default timeouts        // Can be overridden by the MessageContext        if(this.clientProperties.getDefaultConnectionTimeout()>0) {           cm.getParams().setConnectionTimeout(this.clientProperties.getDefaultConnectionTimeout());        }        if(this.clientProperties.getDefaultSoTimeout()>0) {           cm.getParams().setSoTimeout(this.clientProperties.getDefaultSoTimeout());        }        this.connectionManager = cm;    }        /**     * 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 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")                       && ((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);                                try {                    fault.setFaultDetailString(                         Messages.getMessage("return01",                                             "" + returnCode,                                             method.getResponseBodyAsString()));                    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);            Header contentEncoding =             	method.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING);            if (contentEncoding != null) {            	if (contentEncoding.getValue().            			equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP)) {            		releaseConnectionOnCloseStream =             			new GZIPInputStream(releaseConnectionOnCloseStream);            	} else {                    AxisFault fault = new AxisFault("HTTP",                            "unsupported content-encoding of '"                     		+ contentEncoding.getValue()                            + "' found", null, null);                    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 (int i = 0; i < responseHeaders.length; i++) {                Header responseHeader = responseHeaders[i];                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 (int i = 0; i < headers.length; i++) {                    if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE)) {                        handleCookie(HTTPConstants.HEADER_COOKIE, headers[i].getValue(), msgContext);                    } else if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE2)) {                        handleCookie(HTTPConstants.HEADER_COOKIE2, headers[i].getValue(), msgContext);                    }                }            }            // always release the connection back to the pool if             // it was one way invocation            if (msgContext.isPropertyTrue("axis.one.way")) {                method.releaseConnection();            }                    } catch (Exception e) {            log.debug(e);            throw AxisFault.makeFault(e);        }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -