@Test
public void testByTenantId() throws Exception {
String tenantId="nhs7wd2c";
String defURL = "http://bd.basdoc.com/rest/data/transfer";
URL url = new URL(defURL);
// 打開和URL之間的連接
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");//請求post方式
con.setUseCaches(false); // Post請求不能使用緩存
con.setDoInput(true);// 設置是否從HttpURLConnection輸入,默認值爲 true
con.setDoOutput(true);// 設置是否使用HttpURLConnection進行輸出,默認值爲 false
//設置header內的參數 connection.setRequestProperty("健, "值");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("isTree", "true");
con.setRequestProperty("isLastPage", "true");
//設置body內的參數,put到JSONObject中
JSONObject param = new JSONObject();
param.put("sysId", "diwork");
param.put("tenantId", tenantId);
// 建立實際的連接
con.connect();
// 得到請求的輸出流對象
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(),"UTF-8");
writer.write(param.toString());
writer.flush();
// 獲取服務端響應,通過輸入流來讀取URL的響應
InputStream is = con.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuffer sbf = new StringBuffer();
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
// 關閉連接
con.disconnect();
// 打印讀到的響應結果
System.out.println("運行結束:"+sbf.toString());
}
HttpURLConnection的post請求傳遞header參數和body參數的具體方法實現
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.