Java调用RestFul接口
使用Java调用RestFul接口,以POST请求为例,以下提供几种方法:
一、通过HttpURLConnection调用
- 1 public String postRequest(String url, String param) {
- 2 StringBuffer result = new StringBuffer();
- 3
- 4 HttpURLConnection conn = null;
- 5 OutputStream out = null;
- 6 BufferedReader reader = null;
- 7 try {
- 8 URL restUrl = new URL(url);
- 9 conn = (HttpURLConnection) restUrl.openConnection();
- 10 conn.setRequestMethod("POST");
- 11 conn.setDoOutput(true);
- 12 conn.setDoInput(true);
- 13
- 14 conn.setRequestProperty("accept", "*/*");
- 15 conn.setRequestProperty("connection", "Keep-Alive");
- 16 conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
- 17 conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
- 18
- 19 conn.connect();
- 20 out = conn.getOutputStream();
- 21 out.write(param.getBytes());
- 22 out.flush();
- 23
- 24 int responseCode = conn.getResponseCode();
- 25 if(responseCode != 200){
- 26 throw new RuntimeException("Error responseCode:" + responseCode);
- 27 }
- 28
- 29 String output = null;
- 30 reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
- 31 while((output=reader.readLine()) != null){
- 32 result.append(output);
- 33 }
- 34 } catch (Exception e) {
- 35 e.printStackTrace();
- 36 throw new RuntimeException("调用接口出错:param+"+param);
- 37 } finally {
- 38 try {
- 39 if(reader != null){
- 40 reader.close();
- 41 }
- 42 if(out != null){
- 43 out.close();
- 44 }
- 45 if(conn != null){
- 46 conn.disconnect();
- 47 }
- 48 } catch (Exception e2) {
- 49 e2.printStackTrace();
- 50 }
- 51 }
- 52
- 53 return result.toString();
- 54 }
二、通过Spring提供的RestTemplate模板调用
- 1 public class RestTemplateUtil {
- 2
- 3 @Autowired
- 4 private RestTemplate restTemplate;
- 5
- 6 @Bean
- 7 public RestTemplate restTemplate(){
- 8 RestTemplate template = new RestTemplate();
- 9 // messageConverters是RestTemplate的一个final修饰的List类型的成员变量
- 10 // messageConverters的第二个元素存储的是StringHttpMessageConverter类型的消息转换器
- 11 // StringHttpMessageConverter的默认字符集是ISO-8859-1,在此处设置utf-8字符集避免产生乱码
- 12 template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("utf-8")));
- 13 return template;
- 14 }
- 15
- 16 public String post(String url, String jsonParam){
- 17 // 自定义请求头
- 18 HttpHeaders headers = new HttpHeaders();
- 19 headers.setContentType(MediaType.APPLICATION_JSON);
- 20 headers.setAcceptCharset(Collections.singletonList(Charset.forName("utf-8")));
- 21 headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
- 22
- 23 // 参数
- 24 HttpEntity<String> entity = new HttpEntity<String>(jsonParam, headers);
- 25 // POST方式请求
- 26 ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
- 27 if(responseEntity == null){
- 28 return null;
- 29 }
- 30
- 31 return responseEntity.getBody().toString();
- 32 }
- 33
- 34 }
三、通过HttpClient调用
- 1 public class HttpClientUtil {
- 2
- 3 public String post(String url, Map<String, Object> pramMap) throws Exception {
- 4 String result = null;
- 5 // DefaultHttpClient已过时,使用CloseableHttpClient替代
- 6 CloseableHttpClient closeableHttpClient = null;
- 7 CloseableHttpResponse response = null;
- 8 try {
- 9 closeableHttpClient = HttpClients.createDefault();
- 10 HttpPost postRequest = new HttpPost(url);
- 11 List<NameValuePair> pairs = new ArrayList<>();
- 12 if(pramMap!=null && pramMap.size() > 0){
- 13 for (Map.Entry<String, Object> entry : pramMap.entrySet()) {
- 14 pairs.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
- 15 }
- 16 }
- 17 UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(pairs, "utf-8");
- 18 postRequest.setEntity(formEntity);
- 19
- 20 response = closeableHttpClient.execute(postRequest);
- 21 if(response!=null && response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
- 22 result = EntityUtils.toString(response.getEntity(), "utf-8");
- 23 }else{
- 24 throw new Exception("post请求失败,url" + url);
- 25 }
- 26
- 27 } catch (Exception e) {
- 28 e.printStackTrace();
- 29 throw e;
- 30 } finally {
- 31 try {
- 32 if(response != null){
- 33 response.close();
- 34 }
- 35 if(closeableHttpClient != null){
- 36 closeableHttpClient.close();
- 37 }
- 38 } catch (IOException e) {
- 39 e.printStackTrace();
- 40 }
- 41 }
- 42
- 43 return result;
- 44 }
- 45
- 46 }
Java调用RestFul接口的更多相关文章
- 三种方法实现java调用Restful接口
1,基本介绍 Restful接口的调用,前端一般使用ajax调用,后端可以使用的方法比较多, 本次介绍三种: 1.HttpURLConnection实现 2.HttpClient实现 3.Spring ...
- java调用restful接口的方法
Restful接口的调用,前端一般使用ajax调用,后端可以使用的方法如下: 1.HttpURLConnection实现 2.HttpClient实现 3.Spring的RestTemplate
- Java 调用Restful API接口的几种方式--HTTPS
摘要:最近有一个需求,为客户提供一些Restful API 接口,QA使用postman进行测试,但是postman的测试接口与java调用的相似但并不相同,于是想自己写一个程序去测试Restful ...
- 三种方法实现调用Restful接口
1.基本介绍 Restful接口的调用,前端一般使用ajax调用,后端可以使用的方法比较多, 本次介绍三种: 1.HttpURLConnection实现 2.HttpClient实现 3.Spring ...
- Java调用webservice接口方法
java调用webservice接口 webservice的 发布一般都是使用WSDL(web service descriptive langu ...
- python 调用RESTFul接口
本周需要将爬虫爬下来的数据入库,因为之前已经写好PHP的接口的,可以直接通过python调用PHP接口来实现,所以把方法总结一下. //python编码问题,因为好久用,所以很容易出现 # -*- c ...
- Java 调用http接口(基于OkHttp的Http工具类方法示例)
目录 Java 调用http接口(基于OkHttp的Http工具类方法示例) OkHttp3 MAVEN依赖 Http get操作示例 Http Post操作示例 Http 超时控制 工具类示例 Ja ...
- (二)通过JAVA调用SAP接口 (增加一二级参数)
(二)通过JAVA调用SAP接口 (增加一二级参数) 一.建立sap连接 请参考我的上一篇博客 JAVA连接SAP 二.测试项目环境准备 在上一篇操作下已经建好的环境后,在上面的基础上新增类即可 三. ...
- Java方法通过RestTemplate调用restful接口
背景:项目A需要在代码内部调用项目B的一个restful接口,该接口是POST方式,header中 Authorization为自定义内容,主要传输的内容封装在body中,所以使用到了RestTemp ...
随机推荐
- Echarts数据可视化,easyshu图表集成。
介绍: ECharts,一个使用 JavaScript 实现的开源可视化库,可以流畅的运行在 PC 和移动设备上,兼容当前绝大部分浏览器(IE8/9/10/11,Chrome,Firefox,Sa ...
- JavaDailyReports10_15
2020-10-15 16:12:16 今天学习了如何实现倒计时控制程序的运行: 1 package timer; 2 3 import java.util.Calendar; 4 import ja ...
- CSDN中的MARKDOWN编辑器如何快速复制粘贴图片?
前言 我们在使用csdn的markdown编辑器复制其它网站图片,按住ctrl+C复制选择图片,然后按ctrl+V粘贴图片到md编辑器无任何反应!markdown编辑器每次都没法复制粘贴截图! 下面小 ...
- 通过python的socket库实现简易即时通讯小程序
前言 最近学习了一下有关tcp协议和socket有关的知识,看到许多socket实战都喜欢教如何做一个聊天程序,于是想着试试能不能不看教程自己写一个.当然我没太多时间做一个像qq一样的ui界面,所以做 ...
- Apache htaccess 中的RewriteCond 规则介绍 (转)
apache 模块mod_rewrite 提供了一个基于正则表达式分析器的重写引擎来实时重写URL请求.它支持每个完整规则可以拥有不限数量的子规则以及附加条件规则的灵活而且强大的URL操作机制.此UR ...
- 添加/删除/读写c盘文件——c#
一.前言: 有时候我们为自己的程序添加配置文件,如tet.ini.xml等文件,又或者保存软件运行时的日志 当我们把软件打包后,默认安装在c盘,而配置文件也会跟随生成在安装目录下 此时你会发现,配置文 ...
- [Leetcode刷题]——链表
一.找出两个链表的交点 160.相交链表(easy)2021-01-05 编写一个程序,找到两个单链表相交的起始节点 如下面的两个链表,在c1 处相交: public class Soluti ...
- 十八般武艺玩转GaussDB(DWS)性能调优:路径干预
摘要:路径生成是表关联方式确定的主要阶段,本文介绍了几个影响路径生成的要素:cost_param, scan方式,join方式,stream方式,并从原理上分析如何干预路径的生成. 一.cost模型选 ...
- C# 请求被中止: 未能创建 SSL/TLS 安全通道。 设置SecurityProtocol无效
今天为了获取一张图片,用了一段代码: ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateV ...
- python--or 和 and 表达式
or表达式: 两边为一真一假,返回真: 两边都为假,返回右边: 两边都为真,返回左边: and表达式: 两边为一真一假,返回假: 两边都为假,返回左边: 两边都为真,返回右边: