JAVA调用远程接口时模拟发送数据-json格式、x-www-form-urlencoded格式、文件+参数格式
实习期结束,总结一下实习时遇到的一些以前不常用的代码,以方便下次用到时取用,代码不涉及公司机密,需要根据自己的需要进行一定的修改!如有错误欢迎指正!
一个需求是项目的某些接口需要调用外部的接口,由于发送的数据格式各不相同,写了一个工具类根据需要调用,以下是工具类中几个函数。
1.json格式
private static String sendJson(String json, String url) {
// json表示发送的数据,url表示请求的路径
// result 是标识调用后该url返回的结果 String result = null; try { CloseableHttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(url); post.addHeader("Authorization", "Basic YWRtaW46"); StringEntity s = new StringEntity(json, "utf-8"); s.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); post.setEntity(s); // 发送请求 HttpResponse httpResponse = null; httpResponse = client.execute(post); // 获取响应输入流 InputStream inStream = httpResponse.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader( inStream, "utf-8")); StringBuilder strber = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { strber.append(line + "\n"); } inStream.close(); result = strber.toString(); } catch (IOException e) { e.printStackTrace(); } return result; }
2.x-www-form-urlencoded格式
public static String sendXwww(String json, String url) { // 设置请求头 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); RestTemplate restTemplate = new RestTemplate(); MultiValueMap<String, String> forms = new LinkedMultiValueMap<String, String>(); JSONObject object = JSONObject.parseObject(json); for (String key : object.keySet()) { forms.put(key, Collections.singletonList(object.getString(key))); } HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<MultiValueMap<String, String>>(forms, headers); //获取返回数据 String body = restTemplate.postForObject(url, httpEntity, String.class); return body; }
3.发送文件与其他参数格式
public static String senFile(String url, String filepath, Map<String, String> paramMap) {
// filepath表示文件路径 paramMap表示其他参数 // 创建httpPost HttpPost httpPost = new HttpPost(url); CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; org.apache.http.HttpEntity entity = null; String responseContent = null; try { File file = new File(filepath); // 设置参数 MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); //调用的url的文件的参数是file 需要根据调用的url需要的参数进行修改 multipartEntityBuilder.addBinaryBody("file", file);//表单中其他参数 if (paramMap != null) { for (Map.Entry<String, String> entry : paramMap.entrySet()) { multipartEntityBuilder.addPart(entry.getKey(), new StringBody(entry.getValue(), ContentType.create("text/plain", Consts.UTF_8))); } } org.apache.http.HttpEntity reqEntity = multipartEntityBuilder.build(); httpPost.setEntity(reqEntity); // 创建默认的httpClient实例. httpClient = HttpClients.createDefault(); // 执行请求 response = httpClient.execute(httpPost); entity = response.getEntity(); responseContent = EntityUtils.toString(entity, "UTF-8"); } catch (Exception e) { logger.error("<<<<<< HttpUtil sendData error cause {}", e); } finally { try { // 关闭连接,释放资源 if (response != null) { response.close(); } if (httpClient != null) { httpClient.close(); } } catch (IOException e) { logger.error("<<<<<< HttpUtil sendData error cause {}", e); } } return responseContent; }