写一段java代码实现获取微信accesstoken
时间: 2024-04-04 14:32:21 浏览: 63
【ASP.NET编程知识】微信公众平台开发之获得ACCESSTOKEN .Net代码解析.docx
好的,下面是获取微信access token的Java代码示例:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class WeChatAccessToken {
public static void main(String[] args) throws IOException {
String appid = "your_appid";
String secret = "your_secret";
String grant_type = "client_credential";
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=" + grant_type + "&appid=" + appid + "&secret=" + secret;
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
bufferedReader.close();
inputStream.close();
connection.disconnect();
System.out.println(stringBuilder.toString());
}
}
```
需要替换代码中的 `your_appid` 和 `your_secret` 为自己的微信公众号的 appid 和 secret。运行代码后,会返回包含 access_token 的 JSON 格式字符串。
阅读全文