调用接口的方法

本文介绍了一种使用Java实现POST请求的方法,通过定义实体类封装参数,将其转换为JSON字符串,然后通过HttpURLConnection发送到指定路径。文章详细展示了如何设置请求头、处理响应并返回结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值