Use HttpURLConnection to send POST request and carry request parameters


1. First create a URL object and specify the requested URL address.

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

2. Call the openConnection() method of the URL object to create the HttpURLConnection object.

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

3. Set the request method to POST.

connection.setRequestMethod("POST");

4. Set the request header, including Content-Type, Content-Length, etc. Among them, Content-Type indicates the format of the request body, and Content-Length indicates the length of the request body.

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

5. Set the connection timeout and read timeout.

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

6. Allow writing and writing data to the server.

connection.setDoOutput(true);

connection.setDoInput(true);

7. Obtain the output stream and write data to the server.

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


The param here is the request parameter, which needs to be converted into a byte array and then written to the output stream.

8. Obtain the response code to determine whether the request is successful.

int statusCode = connection.getResponseCode();

9. Read the response data.

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();


The response here is the response data, which needs to be read as a string before use.
The complete sample code is as follows:

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());

It should be noted that the request parameters in the above sample code are passed in the form of strings. If you need to pass complex request parameters, you can consider using formats such as JSON. At the same time, if the requested URL needs to carry query parameters, you can add query parameters to the URL.

The following uses HttpURLConnection to send POST request parameter type is json

The following is an example of using the HttpURLConnection WeChat applet to send subscription messages

POST request

json assembled into a JSONObject

json looks like this

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

Guess you like

Origin blog.csdn.net/ImisLi/article/details/129946651