日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

使用HttpURLConnection發(fā)送POST請求并攜帶請求參數(shù)

作者:ImisLi 更新時間: 2024-03-25 編程語言


1、先創(chuàng)建URL對象,指定請求的URL地址。

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

2、調用URL對象的openConnection()方法創(chuàng)建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、允許向服務器寫入寫出數(shù)據(jù)。

connection.setDoOutput(true);

connection.setDoInput(true);

7、獲取輸出流,向服務器寫入數(shù)據(jù)。

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


這里的param是請求參數(shù),需要將其轉換為字節(jié)數(shù)組后寫入輸出流。

8、獲取響應碼,判斷請求是否成功。

int statusCode = connection.getResponseCode();

9、讀取響應數(shù)據(jù)。

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是響應數(shù)據(jù),需要將其讀取為字符串后使用。
完整的示例代碼如下所示:

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

需要注意的是,以上示例代碼中的請求參數(shù)是以字符串形式傳遞的,如果需要傳遞復雜的請求參數(shù),可以考慮使用JSON等格式。同時,如果請求的URL需要攜帶查詢參數(shù),可以在URL中添加查詢參數(shù)。

下面使用HttpURLConnection 發(fā)送POST 請求 參數(shù)類型是json

下面是使用HttpURLConnection微信小程序發(fā)送訂閱消息的一個例子

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

//構造發(fā)送給用戶的訂閱消息內容
            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", "西安大學長安學區(qū)");
            }});
            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();
        }

原文鏈接:https://blog.csdn.net/ImisLi/article/details/129946651

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新