用HttpURLConnection 在Java後臺發送請求並接收返回數據

 我們通常做Java後臺接口,是讓前端訪問的,讓前端獲取數據或者做增刪改查,但是有時候,我們做的Java接口是讓其他系統的Java後臺調用的,讓其他系統從我們這個系統獲取數據或者做業務,這樣就要用到HttpURLConnection。本文寫得急,僅貼出樣例供參考。

(1)先寫一個簡單的,只發送請求,不附帶參數。思路是打開一個URL連接,設置請求的方式,獲取輸入流,從流裏面解析

出數據。

@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();
        }
    }
}
(2)用xml 傳送參數

@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) {
			}
		}
	}
}
(3)用form提交參數

@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) {
            }
        }
    }





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章