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

學(xué)無(wú)先后,達(dá)者為師

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

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

作者:ImisLi 更新時(shí)間: 2024-03-25 編程語(yǔ)言


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

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

2、調(diào)用URL對(duì)象的openConnection()方法創(chuàng)建HttpURLConnection對(duì)象。

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

3、設(shè)置請(qǐng)求方法為POST。

connection.setRequestMethod("POST");

4、設(shè)置請(qǐng)求頭,包括Content-Type、Content-Length等。其中Content-Type表示請(qǐng)求體的格式,Content-Length表示請(qǐng)求體的長(zhǎng)度。

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

5、設(shè)置連接超時(shí)和讀取超時(shí)時(shí)間。

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

6、允許向服務(wù)器寫(xiě)入寫(xiě)出數(shù)據(jù)。

connection.setDoOutput(true);

connection.setDoInput(true);

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

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


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

8、獲取響應(yīng)碼,判斷請(qǐng)求是否成功。

int statusCode = connection.getResponseCode();

9、讀取響應(yīng)數(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是響應(yīng)數(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());

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

下面使用HttpURLConnection 發(fā)送POST 請(qǐng)求 參數(shù)類(lèi)型是json

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

POST請(qǐng)求

json組裝成了一個(gè)JSONObject

json類(lèi)似是這樣的

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

//構(gòu)造發(fā)送給用戶(hù)的訂閱消息內(nèi)容
            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", "西安大學(xué)長(zhǎng)安學(xué)區(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);

            //構(gòu)造訂閱消息
            Map subscribeMessage = new HashMap<String, Object>();
            subscribeMessage.put("touser", " 。。。");//填寫(xiě)你的接收者openid
            subscribeMessage.put("template_id", " 填寫(xiě)你的模板ID");//填寫(xiě)你的模板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

  • 上一篇:沒(méi)有了
  • 下一篇:沒(méi)有了
欄目分類(lèi)
最近更新