使用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类似是这样的

{
  "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();
        }