網(wǎng)站首頁(yè) 編程語(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)有了
相關(guān)推薦
- 2023-02-09 go?sync?Once實(shí)現(xiàn)原理示例解析_Golang
- 2022-09-06 一文詳解Python如何優(yōu)雅地對(duì)數(shù)據(jù)進(jìn)行分組_python
- 2022-10-06 python中關(guān)于對(duì)super()函數(shù)疑問(wèn)解惑_python
- 2022-10-22 Go語(yǔ)言同步等待組sync.WaitGroup結(jié)構(gòu)體對(duì)象方法詳解_Golang
- 2022-05-29 利用Python將list列表寫(xiě)入文件并讀取的方法匯總_python
- 2023-03-29 Python之sklearn數(shù)據(jù)預(yù)處理中fit(),transform()與fit_transfor
- 2022-08-12 Qt實(shí)現(xiàn)電子時(shí)鐘_C 語(yǔ)言
- 2022-09-23 Pandas中Apply函數(shù)加速百倍的技巧分享_python
- 欄目分類(lèi)
-
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過(guò)濾器
- Spring Security概述快速入門(mén)
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支