直接复制以下代码, 运行main方法即可获取access_token
package shuyin.printing.weixin.controller;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
@Data
@RestController
public class AccessTokenController {
private static String appid = "你得自己的";
private static String secret = "你得自己的";
private static String json = "";
@RequestMapping("/doGet")
public static String doGet(){
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret );
CloseableHttpResponse response = null;
try {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.setSocketTimeout(5000)
.setRedirectsEnabled(true).build();
httpGet.setConfig(requestConfig);
response = httpClient.execute(httpGet);
HttpEntity responseEntity = response.getEntity();
System.out.println("响应状态为:" + response.getStatusLine());
String json1 = EntityUtils.toString(responseEntity);
System.out.println("打桩测试数据>>>" + json1);
JSONObject jsonObject = JSONObject.parseObject(json1);
String access_token = jsonObject.getString("access_token");
System.out.println("测试数据access_token的值 >>" + access_token);
json = access_token;
if (responseEntity != null) {
System.out.println("响应内容长度为:" + responseEntity.getContentLength());
}else {
System.out.println("返回字符串为空 !!!!!!!!!!!!!");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return json ;
}
public static void main(String[] args) {
System.out.println("开始获取access_token-------");
AccessTokenController.doGet();
}
}