请求(HTTP、SAOP)

环境:J2EE 5.0

HTTP请求工具类

package xxx.util;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.util.IdleConnectionTimeoutThread;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


/**
 * httpClient处理
 */
public class HttpProtocolHandler {


    /** 连接超时时间,缺省为8秒钟 */
    private int  defaultConnectionTimeout = 8000;

    /** 回应超时时间,缺省为30秒钟 */
    private int  defaultSoTimeout = 30000;

    /** 闲置连接超时时间,缺省为60秒钟 */
    private int defaultIdleConnTimeout  = 60000;
    
    /**定义每台主机允许的最大连接数,默认为2*/
    private int defaultMaxConnPerHost = 80;
    
    /**httpConnectionManager管理的最大连接数,默认为20*/
    private int  defaultMaxTotalConn = 100;

    /** 默认等待HttpConnectionManager返回连接超时(只有在达到最大连接数时起作用)*/
    private static final long   defaultHttpConnectionManagerTimeout = 3 * 1000;

    /**  HTTP连接管理器,该连接管理器必须是线程安全的. */
    private HttpConnectionManager connectionManager;
    
    private static HttpProtocolHandler httpProtocolHandler  = new HttpProtocolHandler();   

    /**  工厂方法 */ 
    public static HttpProtocolHandler getInstance() {
        return httpProtocolHandler;
    }
    /**
     * 私有的构造方法
     */
    private HttpProtocolHandler() {
        // 创建一个线程安全的HTTP连接池
        connectionManager = new MultiThreadedHttpConnectionManager();
        connectionManager.getParams().setDefaultMaxConnectionsPerHost(defaultMaxConnPerHost);
        connectionManager.getParams().setMaxTotalConnections(defaultMaxTotalConn);
        connectionManager.getParams().setConnectionTimeout(defaultConnectionTimeout);
        connectionManager.getParams().setSoTimeout(defaultSoTimeout);
        
        connectionManager.getParams().setIntParameter("http.socket.timeout", 30000);  

        
        IdleConnectionTimeoutThread ict = new IdleConnectionTimeoutThread();
        ict.addConnectionManager(connectionManager);
        ict.setConnectionTimeout(defaultIdleConnTimeout);

        ict.start();
    }
    
    /**执行标志*/
    private static boolean execFlag = true;
    /**正在执行文件标志map*/
    private static Map<String, Integer> writingFlagMap = new HashMap<String, Integer>();
    /**恢复次数map*/
    private static Map<String, Integer> reConnectMap = new HashMap<String, Integer>();
    
	public  boolean isExecFlag() {
		return execFlag;
	}
	public  void setExecFlag(boolean execFlag) {
		HttpProtocolHandler.execFlag = execFlag;
	}
	public static Map<String, Integer> getWritingFlagMap() {
		return writingFlagMap;
	}
	public  void setWritingFlagMap(Map<String, Integer> writingFlagMap) {
		HttpProtocolHandler.writingFlagMap = writingFlagMap;
	}

	/* ******************* 以下是请求文件*********************** */
    /**
     * 请求文件
     * @param requestUrl
     * @param savePath
     * @return
     */
    public boolean executeGetFile(String requestUrl,String savePath){
    	HttpClient httpclient = new HttpClient(connectionManager);
        httpclient.getParams().setConnectionManagerTimeout(defaultHttpConnectionManagerTimeout);
        FileOutputStream out = null;
//        System.out.println("http://"+requestUrl);
 		HttpMethod method = new GetMethod("http://"+requestUrl);
 		InputStream in = null;
 		int len = -1;
 		byte[] b = new byte[1024];
 			try {
				httpclient.executeMethod(method);
				in = method.getResponseBodyAsStream();
				if(method.getStatusCode()!=200){
					System.out.println("信息:http://"+requestUrl+"访问失败,刷新信息失败。");
					return false;
				}
				out = new FileOutputStream(new File(savePath));
				while((len=in.read(b))!=-1){
					out.write(b, 0, len);
				}
				out.flush();
			} catch (HttpException e) {
				e.printStackTrace();return false;
			} catch (IOException e) {
				e.printStackTrace();return false;
			}finally{
				 try {
					if(out!=null){out.close();}
				} catch (IOException e) {
					e.printStackTrace();
				}
				 method.releaseConnection();
			}
			return true;
    }
    /**
     * 直接读取文件信息(对于文件不大的)
     * @param requestUrl
     * @return
     */
    public String executeGetString(String requestUrl){
    	HttpClient httpclient = new HttpClient(connectionManager);
        httpclient.getParams().setConnectionManagerTimeout(defaultHttpConnectionManagerTimeout);
 		HttpMethod method = new GetMethod("http://"+requestUrl);
// 		method.setRequestHeader("Cookie","JSESSIONID="+sessionID);
 		method.getParams().setContentCharset("UTF-8");
 		String resultStr = "";
 			try {
				httpclient.executeMethod(method);
				resultStr = method.getResponseBodyAsString();
				if(method.getStatusCode()!=200){
					return null;
				}
			} catch (HttpException e) {
				e.printStackTrace();
				return null;
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}finally{
				 method.releaseConnection();
			}
    	return resultStr;
    }
    /**
     * 直接读取文件信息(对于文件不大的)
     * @param requestUrl
     * @return
     */
    public String executeWSGetString(String requestUrl){
    	HttpClient httpclient = new HttpClient(connectionManager);
		httpclient.getParams().setConnectionManagerTimeout(defaultHttpConnectionManagerTimeout);
		HttpMethod method = new GetMethod("http://" + requestUrl);
		method.setRequestHeader("Sec-WebSocket-Key", "	esAjYnZeGHsnmqBc/BtOfA==");
		method.setRequestHeader("Upgrade", "websocket");
		method.getParams().setContentCharset("UTF-8");
		String resultStr = "";
		try {
			httpclient.executeMethod(method);
			resultStr = method.getResponseBodyAsString();
			if (method.getStatusCode() != 200) {
				return null;
			}
		} catch (HttpException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			method.releaseConnection();
		}
		return resultStr;
    }

	/* ******************* 以下是POST带参数请求*********************** */
    /**
     * POST带参数请求
     * @param requestUrl
     * @param params
     * @return
     */
    public String executePostReq(String requestUrl,Map<String, String> params){
    	HttpClient httpclient = new HttpClient(connectionManager);
        httpclient.getParams().setConnectionManagerTimeout(defaultHttpConnectionManagerTimeout);
// 		PostMethod pmethod = new PostMethod("http://"+requestUrl);
 		PostMethod pmethod = new PostMethod(requestUrl);
 		NameValuePair[] nvps = new NameValuePair[params.size()];
 		Set<String> keys1 = params.keySet();
 		int i = 0;
 		for(String name1:keys1){
 			NameValuePair p = new NameValuePair(name1,params.get(name1));
 			nvps[i] = p;
 			i++;
 		}
 		pmethod.setRequestBody(nvps);
 		pmethod.getParams().setContentCharset("UTF-8");
		try {
			httpclient.executeMethod(pmethod);
			if(pmethod.getStatusCode()!=200){
				return null;
			}
			String resultStr = pmethod.getResponseBodyAsString();
			return resultStr;
		} catch (HttpException e) {
			e.printStackTrace();return null;
		} catch (IOException e) {
			e.printStackTrace();return null;
		}finally{
			 pmethod.releaseConnection();
		}
    }
    
    
    /**
     * POST带参数请求
     * @param requestUrl
     * @param paramsStr
     * @return
     */
    public String executePostReq1(String requestUrl,String paramsStr){
    	HttpClient httpclient = new HttpClient(connectionManager);
        httpclient.getParams().setConnectionManagerTimeout(defaultHttpConnectionManagerTimeout);
 		PostMethod pmethod = new PostMethod(requestUrl);
 		pmethod.setRequestBody(paramsStr);
 		pmethod.getParams().setContentCharset("UTF-8");
 		pmethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
 		pmethod.addRequestHeader("Content-Type","text/html;charset=utf-8");
		try {
			httpclient.executeMethod(pmethod);
			if(pmethod.getStatusCode()!=200){
				return null;
			}
			String resultStr = pmethod.getResponseBodyAsString();
			return resultStr;
		} catch (HttpException e) {
			e.printStackTrace();return null;
		} catch (IOException e) {
			e.printStackTrace();return null;
		}finally{
			 pmethod.releaseConnection();
		}
    }
   
}

  SOAP请求工具类

package xxx.util;

import javax.xml.namespace.QName;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPHeaderElement;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPElement;
import javax.xml.ws.Dispatch;
import javax.xml.ws.Service;
import javax.xml.ws.Service.Mode;
import javax.xml.ws.soap.SOAPBinding;

import java.net.URL; 
import java.util.Map;
import java.util.Set;

import javax.activation.DataHandler;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Node;

public class SoapSender {
	private MessageFactory msgFactory;
	private static SoapSender instance = new SoapSender();
	
	private  SoapSender(){
		try {
			//创建消息工厂
			msgFactory = MessageFactory.newInstance();
	      } catch (SOAPException e) {
	         e.printStackTrace();
	         throw new RuntimeException(e);
	      }
	}
	public static SoapSender getInstance() {
		return instance;
	}
	public MessageFactory getMessageFactory() {
		return msgFactory;
	}
	/* ******************* 以下是创建SOAPMessage*********************** */
	/**
	 * 创建一个默认的SOAPMessage
	 * @return
	 */
	public SOAPMessage getMessage() throws SOAPException {
		return msgFactory.createMessage();
	}
	/**
	 * 创建SOAPMessage
	 * @param params
	 * @return
	 */
	public SOAPMessage getMessage(Map<String, String> params) throws SOAPException, Exception {
		// 创建消息对象
		SOAPMessage message = msgFactory.createMessage();
		// 获得一个SOAPPart对象
		SOAPPart soapPart = message.getSOAPPart();
		// 获得信封
		SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

//		// 获得消息头
//		SOAPHeader soapHeader = soapEnvelope.getHeader();
//		// 添加头元素
//		SOAPHeaderElement headerElement = soapHeader.addHeaderElement(soapEnvelope.createName("Fault", "soapenv","http://www.xxx.cn"));
//		headerElement.addTextNode("JWS0229043");

		// *****************创建soap消息主体*****************
		SOAPBody soapBody = soapEnvelope.getBody();
		// 添加消息主体
//		Name bodyName = soapEnvelope.createName("INFO", "SOAP-ENV","http://www.xxx.cn");
		Name bodyName = soapEnvelope.createName("INFO");
		SOAPBodyElement bodyElement = soapBody.addBodyElement(bodyName);
		Set<String> keys = params.keySet();
		int i = 0;
 		for(String name:keys){
			Name eleName = soapEnvelope.createName(name);
			SOAPElement se = bodyElement.addChildElement(eleName);
//			se.addChildElement("ServiceCode").addTextNode("10000061");
			se.addTextNode(params.get(name));
 			i++;
 		}
		// *************************************************

//		// 添加SOAP附件
//		URL url = new URL("http://xxx/1.jpg");
//		DataHandler dataHandler = new DataHandler(url);//use the JAF
//		message.addAttachmentPart(message.createAttachmentPart(dataHandler));

		// 更新SOAP消息
		message.saveChanges();
		return message;
	}
	/**
	 * 创建SOAPMessage
	 * @param headers
	 * @param filePath:soap格式文件路径
	 * @return
	 */
	public SOAPMessage getMessage(MimeHeaders headers, String filePath) throws IOException, SOAPException {
//		filePath = Thread.currentThread().getContextClassLoader().getResource("SOAPMessageResp.xml").getPath();
		InputStream is = new FileInputStream(filePath);
		SOAPMessage message = msgFactory.createMessage(headers, is);
		is.close();
		return message;
	}
	/* ******************* 以下是发送SOAP请求*********************** */
	/**
	 * 发送SOAP请求
	 * @param requestUrl
	 * @param message
	 */
	public void send(String requestUrl,SOAPMessage message) throws SOAPException, IOException {
		//创建SOAP连接
		SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
		SOAPConnection sc = scf.createConnection();
		/*
		 * 实际的消息是使用 call()方法发送的,该方法接收消息本身和目的地作为参数,并返回第二个 SOAPMessage 作为响应。
		 * call方法的message对象为发送的soap报文,url为mule配置的inbound端口地址。
		 */
		URL urlEndpoint = new URL(requestUrl); 
		// 响应消息
		SOAPMessage response = sc.call(message, urlEndpoint);
		// *************************************************
		if (response != null) {
			//输出SOAP消息到控制台
			System.out.println("Receive SOAP message:");
			response.writeTo(System.out);
		} else {
			System.err.println("No response received from partner!");
		}
		// *************************************************
		// 关闭连接
		sc.close();
	}
	public void send1(String requestUrl,SOAPMessage message) throws SOAPException, Exception{
		//创建SOAP连接
		SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
		SOAPConnection sc = scf.createConnection();
		//发送SOAP消息到目的地,并返回一个消息
		URL urlEndpoint = new URL(requestUrl);
		SOAPMessage response = sc.call(message, urlEndpoint);
		// *************************************************
		response.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, "utf-8");
		// 打印服务端返回的soap报文供测试
		System.out.println("Receive SOAP message:");
		// 创建soap消息转换对象
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		// 提取消息内容
		Source sourceContent = response.getSOAPPart().getContent();
		// Set the output for the transformation
		StreamResult result = new StreamResult(System.out);
		transformer.transform(sourceContent, result);
		// *************************************************
		// 关闭连接
		sc.close();

		// *************************************************
		/* 模拟客户端A,异常处理测试*/
		SOAPBody ycBody = response.getSOAPBody();
		Node ycResp = ycBody.getFirstChild();
		System.out.print("returnValue:"+ycResp.getTextContent());
	}
	/**
	 * 发送SOAP请求
	public void send1(String requestUrl,SOAPMessage request) {
		//定义serviceName对应的QName,第一个参数是对应的namespace
	    QName serviceName = new QName("http://xxx.com/", "SOAPMessageService");
	    //定义portName对应的QName
	    QName portName = new QName("http://xxx.com/", "SOAPMessagePort");
	    //使用serviceName创建一个Service对象,该对象还不能直接跟WebService对象进行交互
	    Service service = Service.create(serviceName);
//		//指定wsdl文件的位置
//		URL wsdl = new URL("http://localhost:8080/test/jaxws/services/SOAPMessage?wsdl");
//		Service service = Service.create(wsdl, serviceName);
	    //创建一个port,并指定WebService的地址,指定地址后我们就可以创建Dispatch了。
	    service.addPort(portName, SOAPBinding.SOAP11HTTP_BINDING, requestUrl);
	    //创建一个Dispatch对象
	    Dispatch<SOAPMessage> dispatch = service.createDispatch(portName, SOAPMessage.class, Mode.MESSAGE);
	    //调用Dispatch的invoke方法,发送一个SOAPMessage请求,并返回一个SOAPMessage响应。
	    SOAPMessage response = dispatch.invoke(request);
	    System.out.println("服务端返回如下: ");
	    try {
			response.writeTo(System.out);
		} catch (Exception e) {}
	}
	 */

}

  测试方法

	public static void main(String[] args) throws SOAPException, Exception {
		
		Map<String, String> params = new HashMap<String, String>();
		params.put("a","1");

		String string="http://xxx/xxx";
		
		/** *************以下是SOAP请求***************** */
		SoapSender sender = SoapSender.getInstance();

		SOAPMessage message = sender.getMessage();
//		SOAPMessage message = sender.getMessage(params);
//		SOAPMessage message = sender.getMessage(null,"D:\\SOAPMessageResp.xml");
		message.writeTo(System.out);
		sender.send(string,message);
		
		/** *************以下是HTTP请求***************** */
//	    HttpProtocolHandler httpProtocolHandler  = HttpProtocolHandler.getInstance();; 
	    
//	    System.out.println(httpProtocolHandler.executePostReq(string, params));
	    
//		System.out.println(string);
//		System.out.println(httpProtocolHandler.executeGetString(string));
	}

  

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。