用HttpURLConnection 在Java後臺傳送請求並接收返回資料
阿新 • • 發佈:2018-12-31
我們通常做Java後臺介面,是讓前端訪問的,讓前端獲取資料或者做增刪改查,但是有時候,我們做的Java介面是讓其他系統的Java後臺呼叫的,讓其他系統從我們這個系統獲取資料或者做業務,這樣就要用到HttpURLConnection。本文寫得急,僅貼出樣例供參考。
(1)先寫一個簡單的,只發送請求,不附帶引數。思路是開啟一個URL連線,設定請求的方式,獲取輸入流,從流裡面解析
出資料。
(2)用xml 傳送引數@RestController public class TestUrlController { @RequestMapping("testUrl") public void testUrl(){ try { String str = "https://www.baidu.com/"; URL url = new URL(str); //得到connection物件。 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //設定請求方式 connection.setRequestMethod("GET"); //連線 connection.connect(); //得到響應碼 int responseCode = connection.getResponseCode(); if(responseCode == HttpURLConnection.HTTP_OK){ //得到響應流 InputStream inputStream = connection.getInputStream(); //獲取響應 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null){ System.out.println(line); } reader.close(); //該乾的都幹完了,記得把連線斷了 connection.disconnect(); } } catch (Exception e) { e.printStackTrace(); } } }
(3)用form提交引數@Controller @RequestMapping("/aa/") public class HefeixinController { private static Logger logger = Logger.getLogger(HefeixinController.class); @RequestMapping(value = "RechargeRequest") @ResponseBody public HashMap RechargeRequest(RechargeVO rechargeVO, HttpServletResponse response) { HashMap resultMap = new HashMap(); String phone = rechargeVO.getPhone(); if ((phone == null) || (phone.trim() == "")) { resultMap.put("Sessionid", "20170815112314125427"); resultMap.put("Retncode", "-2"); resultMap.put("msg", "手機號不能為空!"); return resultMap; } DataInputStream input = null; java.io.ByteArrayOutputStream out = null; try { String UserID = "Bigturntable"; String PIN = "Bigturntable"; String Sessionid = "20170815112314125427"; String Subscriber_id = "86" + phone + "@ims.mnc000.mcc460.3gppnetwork.org";//主賬號 String Balance = "30";//指定充值的時長 String Type = "9";//套餐 String AccessType = "99";//接入型別 String Expirydate = "20180131";//本次充值的套餐截止日期 //String Rechargetime="20180123"; Date newDate = new Date(); SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyyMMdd");//日期格式 SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat("yyyyMMddHHmmss");//日期格式 String Rechargetime = simpleDateFormat2.format(newDate);//格式化日期 String ServiceType = "2"; //業務型別 String PackageID = "1011";//服務端配置 //充值交易流水號,唯一標識一筆充值,字母+數字的字串, // 格式:6位接入裝置標識(AAAAAA)+年月日時分秒(Yyyymmddhhmiss)+六位流水號(xxxxxx) String Transid = "hfxdgy" + simpleDateFormat3.format(newDate) + (int) ((Math.random() * 9 + 1) * 100000); String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:comm3=\"http://www.chinatelecom.com.cn/schema/ctcc/common/v2_1\" xmlns:ns2=\"http://tempuri.org/ns2.xsd\">" + "<SOAP-ENV:Header>" + "</SOAP-ENV:Header>" + "<SOAP-ENV:Body>" + "<ns2:RechargeRequest>" + "<AuthValue>" + "<UserID>" + UserID + "</UserID>" + "<PIN>" + PIN + "</PIN>" + "</AuthValue>" + "<Sessionid>" + Sessionid + "</Sessionid>" + "<Subscriber_id>" + Subscriber_id + "</Subscriber_id>" + "<Balance>" + Balance + "</Balance>" + "<Type>" + Type + "</Type>" + "<AccessType>" + AccessType + "</AccessType>" + "<Expirydate>" + Expirydate + "</Expirydate>" + "<Rechargetime>" + Rechargetime + "</Rechargetime>" + "<ServiceType>" + ServiceType + "</ServiceType>" + "<PackageID>" + PackageID + "</PackageID>" + "<Transid>" + Transid + "</Transid>" + "</ns2:RechargeRequest>" + "</SOAP-ENV:Body>" + "</SOAP-ENV:Envelope>"; System.out.println("$$$$$$$$$$$$ 傳送報文是:"); System.out.println(xmlString); byte[] xmlData = xmlString.getBytes(); String urlStr = "http://XX.X.XXX.XX:6000";//介面 //獲得到位置服務的連結 URL url = new URL(urlStr); URLConnection urlCon = url.openConnection();//開啟XX連線 urlCon.setDoOutput(true); urlCon.setDoInput(true); urlCon.setUseCaches(false); urlCon.setConnectTimeout(5000); urlCon.setReadTimeout(5000); //將xml資料傳送到位置服務 urlCon.setRequestProperty("Content-Type", "text/xml"); urlCon.setRequestProperty("Content-length", String.valueOf(xmlData.length)); DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream()); printout.write(xmlData);//把報文傳送到XX的介面 printout.flush(); printout.close(); input = new DataInputStream(urlCon.getInputStream());//獲取XX介面的返回資訊 byte[] rResult; out = new java.io.ByteArrayOutputStream(); byte[] bufferByte = new byte[256]; int l = -1; int downloadSize = 0; while ((l = input.read(bufferByte)) > -1) { downloadSize += l; out.write(bufferByte, 0, l); out.flush(); } rResult = out.toByteArray(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document d = db.parse(new ByteArrayInputStream(rResult)); System.out.println("$$$$$$$$$$$ 返回報文是:"); System.out.println(toStringFromDoc(d)); String SessionidStr = d.getElementsByTagName("Sessionid").item(0).getFirstChild().getNodeValue(); String RetncodeStr = d.getElementsByTagName("Retncode").item(0).getFirstChild().getNodeValue(); resultMap.put("Sessionid", SessionidStr); resultMap.put("Retncode", RetncodeStr); return resultMap; } catch (Exception e) { e.printStackTrace(); resultMap.put("Sessionid", "20170815112314125427"); resultMap.put("Retncode", "-1"); resultMap.put("msg", "伺服器繁忙!"); return resultMap; } finally { try { out.close(); input.close(); } catch (Exception ex) { } } } }
@RequestMapping(value="openMemberRights/") @ResponseBody public Map<String, Object> openMemberRights( HttpServletResponse response, @RequestParam(value="phone", required=true) String phone, @RequestParam(value="productId", required=true) String productId ){ String urlString = "https://XXXXXXXXXXXXXXXX"; Map<String, Object> resultMap = new HashMap(); InputStream inputStream = null; OutputStream outputStream = null; try { //獲取位置服務的地址 URL url = new URL(urlString); //開啟連線 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setConnectTimeout(CONNECT_TIME_OUT); connection.setReadTimeout(CONNECT_TIME_OUT); //設定請求方式 connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); connection.connect(); //電話號碼加密 String mobile = AesUtil.encrypt(phone,APPSCRET.substring(0,16)); //唯一隨機數 String once = new SimpleDateFormat("ssSSSS").format(new Date()) + String.valueOf(Math.random()).substring(2, 8); //引數簽名 HashMap<String,String> hashMap = new HashMap<>(); hashMap.put("app_key",APP_KEY); hashMap.put("version", "1.0"); hashMap.put("sdk_from", "java"); hashMap.put("channel", CHANNEL); hashMap.put("once", once); hashMap.put("productId",productId); hashMap.put("mobile", mobile); String signatur = SignUtil.getNornmalSignature(hashMap,APPSCRET); // 表單引數與get形式一樣,拼接form引數 StringBuffer params = new StringBuffer(); params.append("app_key").append("=").append(APP_KEY).append("&") .append("version").append("=").append("1.0").append("&") .append("sdk_from").append("=").append("java").append("&") .append("channel").append("=").append(CHANNEL).append("&") .append("once").append("=").append(once).append("&") .append("productId").append("=").append(productId).append("&") .append("mobile").append("=").append(mobile).append("&") .append("signature").append("=").append(signatur); byte[] bypes = params.toString().getBytes(); // 輸入引數 outputStream = connection.getOutputStream(); outputStream.write(bypes); //從輸入流中讀取資料 inputStream = connection.getInputStream(); String result = new String(StreamTool.readInputStream(inputStream), "UTF-8"); //關閉連線 connection.disconnect(); System.out.println("返回報文是:"); System.out.println(JsonUtil.getBeanMap(result)); return JsonUtil.getBeanMap(result); } catch (Exception e) { e.printStackTrace(); resultMap.put("error_msg","伺服器錯誤!"); return resultMap; } finally { try { inputStream.close(); outputStream.close(); } catch (Exception e) { } } }