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) {
byte[] data = jsonStr.getBytes();
java.net.HttpURLConnection conn=null;
OutputStream outStream=null;
String msg="";;
try {
java.net.URL url = new java.net.URL(path);
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));
outStream = conn.getOutputStream();
outStream.write(data);
msg = "";
// 如果请求响应码是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();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
outStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}// 关闭流
conn.disconnect();// 断开连接
}
return msg;
}
4,调用,并返回参数
try {
returnMsg =sendPost(messageBeanInfo, sendMessageUrl);
reqJsonMsg=messageBeanInfo;
} catch (IOException e) {
e.printStackTrace();
}