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,如若需要請前往閱讀和下載!歡迎交流、批評和指正!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM