对接第三方平台常用的http工具
对接第三方平台常用的http工具
常用的json坐标
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.61</version> </dependency>
RestTemplate的使用说明(推荐)
00 注入RestTemplate
@Configuration public class MyAutoConfig { @Bean public RestTemplate createRestTemplate() { return new RestTemplate(); } }
String url = "https://ad.oceanengine.com/open_api/oauth2/advertiser/get?access_token={access_token}&app_id={app_id}&secret={secret}"; Map<String, String> map = new HashMap<>(); map.put("access_token", accessToken); map.put("app_id", prop.getAppId()); map.put("secret", prop.getSecret()); // get String forObject = restTemplate.getForObject(url, String.class, map);
//请求地址 String url = "https://ad.oceanengine.com/open_api/2/advertiser/qualification/get/"; //设置请求头 headers HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.add("Access-Token", accessToken); requestHeaders.setContentType(MediaType.APPLICATION_JSON); //设置是请求url MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("advertiser_id", advertiserId.toString()); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url); URI uri = builder.queryParams(paramsMap).build().encode().toUri(); HttpEntity httpEntity = new HttpEntity(requestHeaders); // get ,测试时可以先用String查看效果,如果已定义接收的返回对象,则用将String替换成返回对象 ResponseEntity<String> responseEntity = restTemplate.exchange(uri, HttpMethod.GET, httpEntity, String.class);
String url = "https://ad.oceanengine.com/open_api/oauth2/access_token/"; // headers HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setContentType(MediaType.APPLICATION_JSON); //请求体 Map<String, String> map = new HashMap<>(); map.put("key", value); map.put("secret","值"); String requestBody = JSON.toJSONString(map); // HttpEntity HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, requestHeaders); // post ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);
04 通过url获取文件的byte数组
public byte[] getFileBytesByUrl(String url){ ResponseEntity<byte[]> responseEntity = restTemplate().getForEntity(url, byte[].class); return responseEntity.getBody(); }
05 通过restTemplate上传文件(字节数组)
public JSONObject uploadFile(byte[] bytes ,String type){
//访问的地址
final String uploadFileUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token={}&type={}";
//模拟token
String token = "moc_token";
String url = StrUtil.format(uploadFileUrl, token, type);
//要上传的文件(字节数组)
ByteArrayResource resource = new ByteArrayResource(bytes){
@Override
public String getFilename() {
//重写文件名称
return "aa";
}
};
//参数
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
param.add("Content-Disposition", "form-data");
param.add("name", "testUpload");
param.add("Content-Type", "application/octet-stream");
param.add("filename", resource);
param.add("filelength", bytes.length);
//请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity(param, headers);
//获取结果
ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, request, JSONObject.class);
return responseEntity.getBody();
}
06 post请求表单方式(application/x-www-form-urlencoded)
HttpHeaders headers = new HttpHeaders(); // 请求头 非文件表单提交 headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); //请求体参数 params.add("id", id); HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(params, headers); //发送http请求,返回数据格式为text/html用byte[]接收 ResponseEntity<byte[]> responseEntity = restTemplate.postForEntity(url, httpEntity, byte[].class); //获取响应体中的内容 byte[] responseEntityBody = responseEntity.getBody(); //将byte[]转为JSON格式的字符串 String json = new String(responseEntityBody);
踩坑日记:
接口文档中是get请求,测试怎么都不通时,可以换其他方式比如post
如果post参数里有集合或者数据,将对应的value也转成json格式
map.put("dataList",JSON.toJSONString(Arrays.asList("cost", "show", "avg_show_cost", "click", "ctr")) );
HttpClient的使用说明
00 依赖
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.6</version> </dependency>
String uri="......"; // 打开浏览器 CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(uri); //headers httpPost.setHeader("Access-Token", accessToken); httpPost.setHeader("Content-Type", "application/json"); //requestBody Map<String, String> map = new HashMap<>(); map.put("advertiser_id", advertiserId.toString()); map.put("start_date", startDate); map.put("end_date", endDate); map.put("optimize_target", "click");// todo map.put("page", "1"); map.put("page_size", "2000"); String requestBody = JSON.toJSONString(map); // 将请求实体设置到httpPost对象中 StringEntity stringEntity = new StringEntity(requestBody, Charset.forName("UTF-8")); httpPost.setEntity(stringEntity); CloseableHttpResponse response = httpClient.execute(httpPost);