Java发送http请求,参数形式为json

本文分享了如何使用Java发送HTTP POST请求,参数以JSON格式传递,包括URL构建、连接配置及错误处理,方便快速上手和优化API调用。

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

Java发送http请求,参数形式为json

不介绍知识,哪不懂自己搜。只记录平时用到的,可以给其他人做参考。
需要传递的参数为json形式,比如手机号{“phone”:“123456”}

 public static int sendPost(String mobile,int user_id){
	   
			URL postURL = null;
			HttpURLConnection httpUrl = null;
			String url = "这里换成你需要访问的地址";
			String info = "{\"phone\":\""+mobile+"\"}";;
				try {
					postURL = new URL(url);
					httpUrl = (HttpURLConnection) postURL.openConnection();
					httpUrl.setDoInput(true);
					httpUrl.setDoOutput(true);
					httpUrl.setUseCaches(false);
					httpUrl.setRequestProperty("Content-Type", "application/json;chartset=UTF-8");
					httpUrl.setRequestProperty("Cache-Control", "");
					httpUrl.setRequestProperty("User-Agent", "");
					httpUrl.setRequestProperty("Accept", "");
					httpUrl.setRequestProperty("Pragma", "");
					httpUrl.setRequestMethod("POST");
					/** 发送信息 */
					OutputStreamWriter owwriter = new OutputStreamWriter(httpUrl.getOutputStream(),"utf-8");
					owwriter.append(info);
					owwriter.flush();
					owwriter.close();
					
					if (httpUrl.getResponseCode() == 200) {
//访问成功,这里获取返回的json串并且转为实体类。具体实体类看返回什么自己去定义
						InputStream inputStr = httpUrl.getInputStream();
						byte[] b = new byte[inputStr.available()];
						inputStr.read(b);
						JSONObject jsonObject=JSONObject.fromObject(new String(b));
						(实体类名) bean = (efftiveBean)JSONObject.toBean(jsonObject, 实体类名.class);
						inputStr.close();
						//bean 这里就拿到了bean  业务逻辑自己判断自己写 
					} else {
						logger.info("调用服务返回码为"+httpUrl.getResponseCode());
						logger.info("调用失败,不做优化");
					}
				} catch (Exception e) {
					e.printStackTrace();
					logger.info(e.toString());
					logger.info("调用服务异常  不做优化]");
				}
				return result;
				
			}
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值