实际场景:oa系统对接WTS考勤系统平台,需要用到HTTP请求验证身份,具体实现验证;
public static String post(String path, String params, String mad5) throws Exception {
HttpURLConnection httpConn = null;
BufferedReader in = null;
PrintWriter out = null;
try {
URL url = new URL(path);//将url变成url对象;
httpConn = (HttpURLConnection) url.openConnection();//打开url连接
httpConn.setRequestMethod("POST");//设置请求方式
//这里添加的参数
httpConn.setRequestProperty("Content-type", "application/json; charset=utf-8");
httpConn.setRequestProperty("App_Key", "test");//AppKey:公匙(相当于账号)
httpConn.setRequestProperty("App_Secret", "test");// AppSecret:私匙(相当于密码)
httpConn.setRequestProperty("Time_Stamp", String.valueOf(System.currentTimeMillis()));
httpConn.setRequestProperty("Ip", "1");
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
//发送post请求参数
out = new PrintWriter(httpConn.getOutputStream());
out.println(params);
out.flush();
//读取响应
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
StringBuffer content = new StringBuffer();
String tempStr = "";
in = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
while ((tempStr = in.readLine()) != null) {
content.append(tempStr);
}
return content.toString();
} else {
throw new Exception("请求出现了问题!");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
in.close();
out.close();
httpConn.disconnect();
}
return null;
}