1. 程式人生 > >呼叫介面的方法

呼叫介面的方法

1.定義一個入參的實體類,把要傳的引數封裝
2,新建實體類,並賦值,轉換成json串,例如

MessageBean messageBean=new MessageBean();
	messageBean.setServerNum(messagesMsg);//使用者手機號
	messageBean.setLevel(level);//告警等級
	messageBean.setCreatedDate(new Date());
	messageBean.setContent(contentMsg);
	String messageBeanInfo = JSONObject.toJSONString(messageBean);
				

3,呼叫介面的方法

	public String sendPost(String jsonStr, String path) throws IOException {
		byte[] data = jsonStr.getBytes();
		java.net.URL url = new java.net.URL(path);
		java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url.openConnection();
		conn.setRequestMethod("POST");
		conn.setConnectTimeout(5 * 1000);// 設定連線超時時間為5秒
		conn.setReadTimeout(20 * 1000);// 設定讀取超時時間為20秒
		// 使用 URL 連線進行輸出,則將 DoOutput標誌設定為 true
		conn.setDoOutput(true);

		conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
		// conn.setRequestProperty("Content-Encoding","gzip");
		conn.setRequestProperty("Content-Length", String.valueOf(data.length));
		OutputStream outStream = conn.getOutputStream();// 返回寫入到此連線的輸出流
		outStream.write(data);
		outStream.close();// 關閉流
		String msg = "";// 儲存呼叫http服務後的響應資訊
		// 如果請求響應碼是200,則表示成功
		if (conn.getResponseCode() == 200) {
			// HTTP服務端返回的編碼是UTF-8,故必須設定為UTF-8,保持編碼統一,否則會出現中文亂碼
			BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			msg = in.readLine();
			in.close();
		}
		conn.disconnect();// 斷開連線
		return msg;
	}

4,呼叫,並返回引數

try {
	returnMsg =sendPost(messageBeanInfo, sendMessageUrl);
	reqJsonMsg=messageBeanInfo;
} catch (IOException e) {
	e.printStackTrace();
}