URLConnection版
public RespInfo getAppletCode(AppletCode appletCode){
PrintWriter out = null;
InputStream in = null;
String accessToken = RestTemplateUtil.getAccessToken();
try {
URL realUrl = new URL("https://api.weixin.qq.com/wxa/getwxacode?access_token="+accessToken);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
String path = appletCode.getPath();
if(StringUtils.isEmpty(path)){
return RespInfo.mobiError("path不能为空!");
}
JSONObject jsonObject = new JSONObject();
jsonObject.put("path", appletCode.getPath());
jsonObject.put("width",430);
out.print(jsonObject);
out.flush();
in = conn.getInputStream();
byte[] data = null;
try {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = in.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
data = swapStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
String encode = Base64Encoder.encode(data);
return RespInfo.mobiSuccess(encode);
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return null;
}
## RestTemplate版
```java
public void test(){
RestTemplate a=new RestTemplate();
String accessToken = RestTemplateUtil.getAccessToken();
Map<String,String> param = new HashMap<>();
param.put("path","/path/index/index");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Accept", "application/json");
HttpEntity<Map<String, String>> httpEntity = new HttpEntity<Map<String, String>>(param,headers);
String url="https://api.weixin.qq.com/wxa/getwxacode?access_token="+accessToken;
ResponseEntity<byte[]> postResponseEntity=a.postForEntity(url,httpEntity,byte[].class);
BASE64Encoder encoder=new BASE64Encoder();
String encode = encoder.encode(postResponseEntity.getBody());
System.out.println(encode);
}
}