广告
返回顶部
首页 > 资讯 > 后端开发 > JAVA >使用HttpURLConnection发送POST请求并携带请求参数
  • 793
分享到

使用HttpURLConnection发送POST请求并携带请求参数

javaspringintellij-ideaspringboot 2023-08-31 17:08:56 793人浏览 八月长安
摘要

1、先创建URL对象,指定请求的URL地址。 URL url = new URL("Http://example.com/api"); 2、调用URL对象的openConnection()方法创建HttpURLConnection对象。


1、先创建URL对象,指定请求的URL地址。

URL url = new URL("Http://example.com/api");

2、调用URL对象的openConnection()方法创建HttpURLConnection对象。

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

3、设置请求方法为POST。

connection.setRequestMethod("POST");

4、设置请求头,包括Content-Type、Content-Length等。其中Content-Type表示请求体的格式,Content-Length表示请求体的长度。

connection.setRequestProperty("Content-Type", "application/x-www-fORM-urlencoded");connection.setRequestProperty("Content-Length", String.valueOf(param.getBytes().length));

5、设置连接超时和读取超时时间。

connection.setConnectTimeout(5000);connection.setReadTimeout(5000);

6、允许向服务器写入写出数据。

connection.setDoOutput(true);connection.setDoInput(true);

7、获取输出流,向服务器写入数据。

OutputStream outputStream = connection.getOutputStream();outputStream.write(param.getBytes());outputStream.flush();outputStream.close();


这里的param是请求参数,需要将其转换为字节数组后写入输出流。

8、获取响应码,判断请求是否成功。

int statusCode = connection.getResponseCode();

9、读取响应数据。

InputStream inputStream = statusCode == 200 ? connection.getInputStream() : connection.getErrorStream();BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));StringBuilder response = new StringBuilder();String line;while ((line = reader.readLine()) != null) {    response.append(line);}reader.close();inputStream.close();


这里的response是响应数据,需要将其读取为字符串后使用。
完整的示例代码如下所示:

String param = "name=张三&age=18";URL url = new URL("http://example.com/api");HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("POST");connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");connection.setRequestProperty("Content-Length", String.valueOf(param.getBytes().length));connection.setConnectTimeout(5000);connection.setReadTimeout(5000);connection.setDoOutput(true);OutputStream outputStream = connection.getOutputStream();outputStream.write(param.getBytes());outputStream.flush();outputStream.close();int statusCode = connection.getResponseCode();InputStream inputStream = statusCode == 200 ? connection.getInputStream() : connection.getErrorStream();BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));StringBuilder response = new StringBuilder();String line;while ((line = reader.readLine()) != null) {   response.append(line);}reader.close();inputStream.close();connection.disconnect();System.out.println(response.toString());

需要注意的是,以上示例代码中的请求参数是以字符串形式传递的,如果需要传递复杂的请求参数,可以考虑使用JSON等格式。同时,如果请求的URL需要携带查询参数,可以在URL中添加查询参数。

下面使用HttpURLConnection 发送POST 请求 参数类型是json

下面是使用HttpURLConnection微信小程序发送订阅消息的一个例子

POST请求

json组装成了一个JSONObject

json类似是这样的

{  "touser": "OPENID",  "template_id": "TEMPLATE_ID",  "page": "index",  "data": {      "name01": {          "value": "某某"      },      "amount01": {          "value": "¥100"      },      "thing01": {          "value": "广州至北京"      } ,      "date01": {          "value": "2018-01-01"      }  }}
  try {            URL url = new URL(" https://api.weixin.qq.com/cgi-bin/message/subscribe/send?" +                    "access_token=" +                    "自己的小程序token");            HttpURLConnection connection = (HttpURLConnection) url.openConnection();            connection.setRequestMethod("POST");            connection.setRequestProperty("Content-Type", "application/json");            connection.setDoOutput(true);            connection.setDoInput(true);//构造发送给用户的订阅消息内容            Map messageContent = new HashMap();            messageContent.put("character_string1", new HashMap() {{                put("value", "a123456789");            }});            messageContent.put("amount2", new HashMap() {{                put("value", "1元");            }});            messageContent.put("thing3", new HashMap() {{                put("value", "西安大学长安学区");            }});            messageContent.put("time4", new HashMap() {{                put("value", "2021年10月20日");            }});            messageContent.put("thing5", new HashMap() {{                put("value", "这是备注");            }});            JSONObject messageContentJson = new JSONObject(messageContent);            //构造订阅消息            Map subscribeMessage = new HashMap();            subscribeMessage.put("touser", " 。。。");//填写你的接收者openid            subscribeMessage.put("template_id", " 填写你的模板ID");//填写你的模板ID            subscribeMessage.put("data", messageContentJson);            JSONObject subscribeMessageJson = new JSONObject(subscribeMessage);            String s1 = subscribeMessageJson.toString();            System.out.println("String:" + s1);            byte[] bytes = s1.getBytes();            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());            wr.write(bytes);            wr.close();            int statusCode = connection.getResponseCode();            InputStream inputStream = statusCode == 200 ? connection.getInputStream() : connection.getErrorStream();            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));            StringBuilder response = new StringBuilder();            String line;            while ((line = reader.readLine()) != null) {                response.append(line);            }            reader.close();            inputStream.close();            connection.disconnect();            System.out.println(response.toString());            connection.disconnect();        } catch (Exception e) {            e.printStackTrace();        }

来源地址:https://blog.csdn.net/ImisLi/article/details/129946651

--结束END--

本文标题: 使用HttpURLConnection发送POST请求并携带请求参数

本文链接: https://www.lsjlt.com/news/386296.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作