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

这篇具有很好参考价值的文章主要介绍了使用HttpURLConnection发送POST请求并携带请求参数。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

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类似是这样的文章来源地址https://www.toymoban.com/news/detail-442867.html

{
  "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<String, Object>();
            messageContent.put("character_string1", new HashMap<String, Object>() {{
                put("value", "a123456789");
            }});
            messageContent.put("amount2", new HashMap<String, Object>() {{
                put("value", "1元");
            }});
            messageContent.put("thing3", new HashMap<String, Object>() {{
                put("value", "西安大学长安学区");
            }});
            messageContent.put("time4", new HashMap<String, Object>() {{
                put("value", "2021年10月20日");
            }});
            messageContent.put("thing5", new HashMap<String, Object>() {{
                put("value", "这是备注");
            }});
            JSONObject messageContentJson = new JSONObject(messageContent);

            //构造订阅消息
            Map subscribeMessage = new HashMap<String, Object>();
            subscribeMessage.put("touser", " 。。。");//填写你的接收者openid
            subscribeMessage.put("template_id", " 填写你的模板ID");//填写你的模板ID
            subscribeMessage.put("data", messageContentJson);
            JSONObject subscribeMessageJson = new JSONObject(subscribeMessage);
/*
            String s = subscribeMessageJson.toJSONString();
            System.out.println("JSONString:" + s);
*/
            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();
        }

到了这里,关于使用HttpURLConnection发送POST请求并携带请求参数的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • HttpURLConnection中请求头中携带Token的使用方法

    一般会在头部添加认证信息,如token值或BasicAuth认证的 Authorization值

    2024年02月05日
    浏览(31)
  • Flutter携带JSON参数post请求

    在Flutter中发送带有JSON参数的网络请求,你可以使用HTTP库(如 http 或 dio )来实现。以下是使用 http 库发送网络请求并携带JSON参数的示例: 在上述示例中,首先创建一个参数Map,并将其转换为JSON字符串。然后设置请求头,使其指明请求类型为JSON。最后使用 http.post() 方法发送

    2024年02月14日
    浏览(44)
  • Java 发送Http请求携带中文参数时 请求报400的错误请求

    在 Java 中,URL 中不能直接包含中文字符,因为 URL 规范要求 URL 必须是 ASCII 字符。如果需要在 URL 中传递中文参数,需要对中文参数进行 URL 编码,将其转换为浏览器中的参数形式。可以使用 java.net.URLEncoder 类来进行 URL 编码。

    2024年02月11日
    浏览(32)
  • 使用HuTool的Http工具发送post传递中文参数,请求会乱码的解决方法

    Hutool 是一款功能丰富、易用的Java工具类库,我们在工作中经常会使用它的各种类库方法简化我们的开发,其中我们甚至能通过它的Http工具类直接发送http的各种请求,下面来介绍一下发送post请求时参数中有中文出现乱码的解决方法。 这样就不会造成请求参数出现乱码问题

    2024年02月01日
    浏览(31)
  • 安卓App使用HttpURLConnection发送请求与上传文件

    系统内置http请求工具为 HttpURLConnection httpClient 是 apache 的开源工具 okHttp 使用更简单,语法相对HttpURLConnection也简洁了许多,需要在graddle添加依赖。 本文主要讲解如何使用HttpURConnection向服务器发送Reqest, 保存Response内容,如何上传文件等内容。 step-1: 创建1个URL 对象 step-2: 创建

    2024年02月03日
    浏览(27)
  • axios的put/post请求携带一个string 类型的参数, 前端代码和后端接收方法

    使用axios发送post请求, 后端支持接收单个字段 想要让后端支持接收单个字段,前端就必须是 FormData 格式或 x-www-form-urlencoded 格式,所以参数对象就不能是简单的js对象了,具体代码如下: 后端使用@RequestParam注解接收。 使用axios发送post请求, 后端整体接收json对象 前端代码 da

    2024年02月07日
    浏览(54)
  • 在Vue中使用axios发送post请求时,可能会出现后端无法接收到参数的情况。

    在Vue中使用axios发送post请求时,可能会出现后端无法接收到参数的情况。这个问题的原因是axios默认发送的请求是json格式的,而后端接收的请求是form表单格式的,这就导致后端无法获取json格式的请求参数。解决这个问题可以通过设置axios的请求头部信息,将请求格式设置为

    2024年02月16日
    浏览(35)
  • Postman+Java springboot演示 get post put delete请求并携带(路径 路径问号后 json 表单)参数形式

    我们先创建一个java的springboot工程 在项目中 找到启动类的位置目录 在项目创建一个类 叫 user 我是想将 user 当做一个属性类的 按规范来讲 我们可以创建一个entity包 然后在下面去创建属性类 但这里 我们不想搞那么麻烦了 毕竟只是练习一下 然后 user参考代码如下 这里 只是定

    2024年02月06日
    浏览(36)
  • vue3使用axios发送post请求,后台接收到的参数总是null,使用postman测试后台是能接收数据的

    使用vue3,连基本的请求都失败了,使用浏览器查看post请求,参数中是有值,但是传到后台,每个参数都是null,不知道哪里错了。排除了后台的错误,就剩下了vue代码的错误了。我出错的地方是vue使用axios发送post请求的时候,参数格式写错了。 直接贴代码了,正确的写法 f

    2024年02月13日
    浏览(34)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包