網(wǎng)站首頁 編程語言 正文
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
- 上一篇:沒有了
- 下一篇:沒有了
相關推薦
- 2022-09-05 內置指令、自定義指令(詳細)、全局指令與局部指令
- 2023-01-18 淺析Python的對象拷貝和內存布局_python
- 2022-06-28 C#開發(fā)Winform實現(xiàn)學生管理系統(tǒng)_C#教程
- 2022-01-04 localStorage本地存儲防止參數(shù)丟失
- 2023-07-07 maven查看jar的pom引入來源
- 2022-07-03 無緩沖channel的內存泄漏問題
- 2023-04-11 利用Matlab實現(xiàn)時域分析功能的示例詳解_C 語言
- 2022-09-29 Shell之function函數(shù)的定義及調用示例_linux shell
- 欄目分類
-
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結構-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支