http頁面執行https跨協議請求的解決辦法
阿新 • • 發佈:2019-02-09
有時候,我們需要在彈層中使用跨域跨協議去訪問某個伺服器獲取檢視,樓主就在專案中遇到了這個問題。在一次pos機專案的開發中需要訪問我公司不同專案的伺服器,我們兩個部門的域名、協議都是不一樣的。我需要在https協議下去訪問不同域名的http協議地址,當然在瀏覽器新開一個視窗(window.open(“http://”))就不會有問題,但是這在ajax的回撥函式中彈窗使用就遇到了很大麻煩。
要支援跨域的彈窗還好說,直接使用iframe就可以解決或者jsonp,但是在一個https頁面訪問http協議地址來在彈窗中顯示時瀏覽器會報如下錯誤。
該錯誤是說瀏覽器的同一頁面下不能即訪問https協議,又訪問http協議,這時候請求直接會被瀏覽器攔截。
因為公司需求不能使用新開一頁去載入http地址內容,只能通過彈窗來載入http內容,這樣顯示會比較美觀,樓主查了很多資料也沒能解決跨協議彈窗的問題。但是需求又不能改,樓主只能一直想解決辦法。一次突然想到了以前用Java來執行http請求的例項,這樣就想到了解決方案了。
既然瀏覽器不要我們跨協議訪問,那麼我們可以通過Java程式碼直接模擬http請求獲取到相關返回的輸入流資料,樓主專案中程式碼如下:
/**
* 功能描述: 二維碼支付頁面跨協議跳轉<br>
*
* @param preOrderId 訂單號
* @param useId 使用者id
* @param request 請求
* @return AjaxObj
*/
@RequestMapping("/redirectPay")
public ModelAndView redirectPay(@RequestParam(value="preOrderId",required=true)String preOrderId,
@RequestParam(value="userId",required=true)String userId,HttpServletRequest request){
try {
Store store=this.getStore(request);
String token=preOrderId+store.getStoreId();
token=md5Security(token);
String projectEnvironment=request.getHeader("Host" ).substring(10,13);
LOGGER.info("projectEnvironment:"+projectEnvironment);
String posPaymentUrl="http://order."+projectEnvironment+".com/pospay/order/prepayment.htm?token="
+token+"&preOrderId="+preOrderId+"&userId="+userId;
URL redirectUrl = new URL(posPaymentUrl);
byte[] word=new byte[1024];
String path=request.getSession().getServletContext().getRealPath("/");
path=path+"WEB-INF\\views\\book\\template.ftl;
LOGGER.info("path:"+path);
FileOutputStream fileOutputStream=new FileOutputStream(path);
String byteStr="";
URLConnection connection = (HttpURLConnection) redirectUrl.openConnection();
BufferedInputStream stream=new BufferedInputStream(connection.getInputStream());
while(stream.read(word)!=-1){
byteStr=byteStr+new String(word);
LOGGER.info("資訊:"+new String(word));
}
LOGGER.info("資訊:"+byteStr);
fileOutputStream.write(byteStr.getBytes());
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return new ModelAndView("/book/template.ftl");
}
}