最近被分配干大华摄像头,需要调用第三方接口。java如何调用对方http接口(header和body中的参数传参)
之前调用的钉钉第三方接口都是普通传参,很简单。这次是往请求头和请求体里面传参,做一下记录。
//从配置文件中读取路径 可以写死 "http://。。。。。。。"
String serverURL = "https://www.cloud-dahua/liveList";
StringBuffer sbf = new StringBuffer();
String strRead = null;
URL url = new URL(serverURL);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");//请求post方式
connection.setDoInput(true);
connection.setDoOutput(true);
//header内的的参数在这里set。||connection.setRequestProperty("健, "值");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Authorization", "Bearer 59e0-9fcc-c3faea0e2a6c");
connection.connect();
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(),"UTF-8");
//body参数在这里put到JSONObject中
JSONObject parm = new JSONObject();
parm.put("pageNum", 1);
parm.put("pageSize", 2);
parm.put("storeId", 001);
writer.write(parm.toString());
writer.flush();
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
//sbf.append("\r\n");
}
reader.close();
connection.disconnect();
String results = sbf.toString();
年纪轻轻,不卑不亢,干就完了!