https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN用java代码如何diaoyong
时间: 2023-12-31 14:05:29 浏览: 212
可以使用Java的HttpURLConnection或者HttpClient库来发送HTTP请求调用微信的API。
以下是使用HttpURLConnection的示例代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class WeChatApi {
public static void main(String[] args) {
try {
String accessToken = "YOUR_ACCESS_TOKEN";
String apiUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;
String postData = "YOUR_POST_DATA"; // 根据实际情况填写请求参数
URL url = new URL(apiUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
// 发送POST请求
connection.getOutputStream().write(postData.getBytes("UTF-8"));
// 读取响应数据
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 输出响应数据
System.out.println(response.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
需要替换掉`YOUR_ACCESS_TOKEN`和`YOUR_POST_DATA`为实际的值。其中,`YOUR_POST_DATA`是根据微信API文档中的要求构造的POST请求参数,需要根据实际情况填写。
阅读全文