1. 程式人生 > >http操作,模擬第三方介面回撥通知

http操作,模擬第三方介面回撥通知

可以用來檢驗返回給第三方的迴應SUCCESS是否正確,包括編碼,是否有空格

模擬第三方介面傳送回撥notify

import java.io.IOException;
	import java.io.InputStream;
	import java.io.OutputStream;
	import java.net.HttpURLConnection;
	import java.net.URL;
	
	private static byte[] readContent(final InputStream in, int length) throws IOException {
		byte dataBytes[] = new byte[length];		
		int bytesRead = 0;
		int n = 0;
		int leftbytes = length;
		while (leftbytes > 0
				&& (n = in.read(dataBytes, bytesRead, leftbytes)) != -1) {
			leftbytes = length - bytesRead;
			bytesRead = bytesRead + n;
		}
		return dataBytes;
	}

	public static void main(String args[]){
		try {
			
			URL url = new URL("https://www.1hedai.com/page/style4/yeepayCallBack/SpaceNotify.jsp");
			HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
			urlcon.setReadTimeout(5000);
			urlcon.setDoOutput(true);
			urlcon.setDoInput(true);
			urlcon.setRequestMethod("POST");
			urlcon.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
			OutputStream out = urlcon.getOutputStream();
			
			out.write("測試返回的SUCCESS".getBytes("UTF-8"));
			out.flush();
			out.close();
			
			int length = urlcon.getContentLength();
			InputStream in = urlcon.getInputStream();
			byte[] b = readContent(in, length);
			String result =  new String(b, "UTF-8");
			System.out.println("收到的回撥:" + result + "0");
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}



伺服器接收到notify,併發送回應SUCCESS
//介面回撥
	//列印引數
	System.out.println("+++++++++++++++ space Notify ++++++++++++++++++");
	
	//宣告JSP物件
	try{
		// 驗籤
		//boolean flag = SignUtil.verifySign(sourceMessage, signMsg);
		//out.print("SUCCESS");
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		//response.getWriter().write("SUCCESS");
	
		OutputStream outStream = response.getOutputStream();
		outStream.write("SUCCESS".getBytes("UTF-8"));
		//outStream.flush();
		outStream.close(); 
	}catch(Exception e){
		 e.printStackTrace();
	}