java封装HttpURLConnection发送POST请求实例

一、开发需求
    当银行核心系统某一接口报错时,需要通过ESB调用短信服务将错误及时信息发送给银行科技人员,进而解决问题。
二、开发过程
    封装线程、封装HttpURLConnection网络POST请求、拼接Soap请求报文、加载配置文件发送请求。
三、代码简介
(一)封装线程

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;

/**
 * Encapsulate threads
 * @author Mark
 */
public class HttpCommProcessThread implements Runnable{
	
	byte[] postMsg;
	private int readLen;
	private boolean isStop = false;
	private boolean readOK = false;
	private HttpURLConnection reqConnection = null;
	private Thread readingThread;
	private byte[] buffer = null;
	private Exception exception = null;

	public HttpCommProcessThread(HttpURLConnection reqConnection, byte[] postMsg) {
		this.reqConnection=reqConnection;
		this.postMsg=postMsg;
	}

	public void run() {
		InputStream input = null;
		OutputStream output = null;

		try{
			reqConnection.connect();
			output = reqConnection.getOutputStream();
			if (postMsg != null && postMsg.length >0) {
				output.write(postMsg);
				output.close();
			}

			int responseCode=reqConnection.getResponseCode();
			if(responseCode==500)
				throw new RuntimeException("C30000,Server 500 error:Requested service response exception");
			
			if(responseCode!=200)
				throw new RuntimeException("HttpCommService failed! responseCode = "+responseCode+" msg=" + reqConnection.getResponseMessage());
			
			input = reqConnection.getInputStream();						
			ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
			int len;				
			byte[] buf = new byte[1024];
			readLen = 0;
			while(!isStop){
				len = input.read(buf,0,1024);
				if (len <= 0) {
					this.readOK = true;
					input.close();
					break;
				}else{
					swapStream.write(buf,0,len);
				}
				readLen += len;
			}				
			buffer=new byte[readLen];
			System.arraycopy(swapStream.toByteArray(), 0, buffer, 0, readLen);
		} catch(Exception e) {
			exception = e;
		} finally {
			try{
				reqConnection.disconnect();
				if( input != null )
					input.close();
				if( output != null )
					output.close();

				wakeUp();
			} catch(Exception e) {}
		}
	}

	private synchronized void wakeUp() {
		notifyAll();
	}
	
	public void startUp() {
		this.readingThread = new Thread(this);
		readingThread.setName("HttpCommService reading thread");
		readingThread.start();
	}
	
	public byte[] getMessage() throws Exception {
		
		if( exception != null )
			throw exception;			
		if (!readOK) {
			throw  new RuntimeException("Communication timeout") ;
		}			
		if (readLen <= 0) {
			return new byte[0];
		}
		return buffer;
	}
	
	public synchronized void waitForData(int timeout) {
		try {
			wait(timeout);
		} catch (Exception e) {}
			
		if (!readOK) {
			isStop = true;
			try{
				if( readingThread.isAlive() )
					readingThread.interrupt();
			}catch(Exception e){}
		}
	}

}

(二)封装HttpURLConnection网络POST请求、拼接Soap请求报文、加载配置文件发送请求

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.Random;

import com.iflex.fcr.infra.log.impl.TraceLogger;

/**
 * Send message to technicians to deal with problems
 * @author Mark
 */
public class HttpSendSmsProcessor {
	
	public static final String THIS_COMPONENT_NAME = "HttpSendSmsProcessor";
	private static final String SOAP_ESB = "/service.properties";
	private static final Properties soaESBMap = new Properties();

	public HttpSendSmsProcessor() {
		init();
	}

	/**
	 * Initialize load profile
	 */
	public static void init() {
		intPropertyFile(soaESBMap, SOAP_ESB);
	}
	private static void intPropertyFile(Properties target, String name) {
		String METHOD_NAME = "intPropertyFile";
		try {
			target.load(HttpSendSmsProcessor.class.getResourceAsStream(name));
		} catch (IOException ex) {
			TraceLogger.trace(THIS_COMPONENT_NAME, METHOD_NAME, ex.getMessage());
		}
	}

	/**
	 * ESB service URL
	 * @param paramName
	 * @return
	 */
	public static String getESBServiceURL(String paramName) {
		return soaESBMap.getProperty(paramName);
	}
	
	/**
	 * Phone numbers
	 * @param paramName
	 * @return
	 */
	public static String[] getTelephoneNo(String paramName) {
		return soaESBMap.getProperty(paramName).split(",");
	}
	
	/**
	 * Send message to technologists
	 * @param errMsg
	 * @param timeout
	 * @return
	 */
	public String executeSendSms (String errMsg, int timeout) {
		HttpURLConnection reqConnection;
		String[] telephones = getTelephoneNo("telephoneNo");
		String httpURL = getESBServiceURL("url");
		byte[] msg = null;
		
		try {
			for (String telephone : telephones) {
				reqConnection = HttpPost(httpURL);
				HttpCommProcessThread rec = new HttpCommProcessThread(reqConnection, requestSoapMsgByte(errMsg, telephone));
				
				rec.startUp();
				rec.waitForData(timeout);
				msg = rec.getMessage();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return new String(msg);
	}
	
	
	/**
	 * HttpURLConnection object request parameter settings
	 * @param httpURL
	 * @return
	 * @throws Exception
	 */
	public static HttpURLConnection HttpPost (String httpURL) throws Exception {
		URL reqUrl = new URL(httpURL);
		HttpURLConnection reqConnection = (HttpURLConnection) reqUrl.openConnection();

		reqConnection.setRequestProperty("SOAPAction", "");
		reqConnection.setRequestProperty("Content-Type", "application/soap+xml;charset=utf-8");
		reqConnection.setRequestMethod("POST");
		reqConnection.setDoInput(true);
		reqConnection.setDoOutput(true);
		
		return reqConnection;
	}
	
	/**
	 * Soap request message
	 * @param errMsg
	 * @param telephoneNo
	 * @return
	 * @throws Exception
	 */
	public static byte[] requestSoapMsgByte(String errMsg, String telephoneNo) throws Exception {
		String systemTime = new SimpleDateFormat("HHmmss").format(new Date());
		String systemDate = new SimpleDateFormat("yyyyMMdd").format(new Date());
		int userNumber = new Random().nextInt(100);
		String userReferenceNo = "FCR"+systemDate+systemTime+userNumber;
		int sysNumber = new Random().nextInt(1000000);
		String sysReferenceNo = "FCR"+systemDate+systemTime+sysNumber;
		
		StringBuffer stringBuffer = new StringBuffer(
				"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:esb=\"http://esb.soa.sxccb.com\" xmlns:osp=\"http://osp.founder.com\" xmlns:xsd=\"http://osp.founder.com/xsd\">"+
				   "<soapenv:Header>"+
				   "<esb:RequestEsbHeader>"+
							"<esb:Operation>processRequest</esb:Operation>"+
							"<esb:RequestSystemID>FCR</esb:RequestSystemID>"+
							"<esb:RequestSubsystemID>SVR</esb:RequestSubsystemID>"+
							"<esb:Version>1.0</esb:Version>"+
							"<esb:Service>SMS0031</esb:Service>"+
							"<esb:RequestSystemTime>"+systemTime+"</esb:RequestSystemTime>"+
							"<esb:RequestSystemDate>"+systemDate+"</esb:RequestSystemDate>"+
							"<esb:UserReferenceNo>"+userReferenceNo+"</esb:UserReferenceNo>"+
							"<esb:SystemReferenceNo>"+sysReferenceNo+"</esb:SystemReferenceNo>"+
						"</esb:RequestEsbHeader>"+
						"<osp:RequestOspHeader>"+
							"<osp:SYS_HEAD>"+
								"<xsd:SERVICE_CODE>SMS0031</xsd:SERVICE_CODE>"+
								"<xsd:TRAN_CODE>SMS0031</xsd:TRAN_CODE>"+
								"<xsd:BRANCH>0900</xsd:BRANCH>"+
								"<xsd:USER_ID>S0900</xsd:USER_ID>"+
								"<xsd:CHANNEL_TYPE>FCR</xsd:CHANNEL_TYPE>"+
								"<xsd:AUTH_FLAG>N</xsd:AUTH_FLAG>"+
								"<xsd:TIMESTAMP>"+systemTime+"</xsd:TIMESTAMP>"+
								"<xsd:TRAN_DATE>"+systemDate+"</xsd:TRAN_DATE>"+
								"<xsd:USER_REFERENCE>"+userReferenceNo+"</xsd:USER_REFERENCE>"+
								"<xsd:CHANNEL_NO>"+sysReferenceNo+"</xsd:CHANNEL_NO>"+
							"</osp:SYS_HEAD>"+
							"<osp:APP_HEAD/>"+
						"</osp:RequestOspHeader>"+
					"</soapenv:Header>"+
					"<soapenv:Body>"+
						"<osp:bizSMS0031InputType>"+
							"<osp:param>"+
								"<xsd:TelephoneNo>"+telephoneNo+"</xsd:TelephoneNo>"+
								"<xsd:mobileOperators/>"+
								"<xsd:text>"+errMsg+"</xsd:text>"+
							"</osp:param>"+
						"</osp:bizSMS0031InputType>"+
					"</soapenv:Body>"+
				"</soapenv:Envelope>"
				);
		return stringBuffer.toString().getBytes("utf-8");
	}
}
#配置文件
url=
telephoneNo=159****2890,131****4242

(三)发送请求测试

public class ExecuteSendSmsTest {
	@Test
	public void executeSendSmsTest() {
		new HttpSendSmsProcessor().executeSendSms("报错啦!抓紧去银行修改bug!", 20000000);
	}
}

四、资源获取
    源码已上传至github,如若需要请前往阅读和下载!欢迎交流、批评和指正!

原创文章 3 获赞 1 访问量 293

猜你喜欢

转载自blog.csdn.net/mark_blogs/article/details/106070311
今日推荐