使用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接口的更多相关文章

  1. 三种方法实现java调用Restful接口

    1,基本介绍 Restful接口的调用,前端一般使用ajax调用,后端可以使用的方法比较多, 本次介绍三种: 1.HttpURLConnection实现 2.HttpClient实现 3.Spring ...

  2. java调用restful接口的方法

    Restful接口的调用,前端一般使用ajax调用,后端可以使用的方法如下: 1.HttpURLConnection实现 2.HttpClient实现 3.Spring的RestTemplate

  3. Java 调用Restful API接口的几种方式--HTTPS

    摘要:最近有一个需求,为客户提供一些Restful API 接口,QA使用postman进行测试,但是postman的测试接口与java调用的相似但并不相同,于是想自己写一个程序去测试Restful ...

  4. 三种方法实现调用Restful接口

    1.基本介绍 Restful接口的调用,前端一般使用ajax调用,后端可以使用的方法比较多, 本次介绍三种: 1.HttpURLConnection实现 2.HttpClient实现 3.Spring ...

  5. Java调用webservice接口方法

                             java调用webservice接口   webservice的 发布一般都是使用WSDL(web service descriptive langu ...

  6. python 调用RESTFul接口

    本周需要将爬虫爬下来的数据入库,因为之前已经写好PHP的接口的,可以直接通过python调用PHP接口来实现,所以把方法总结一下. //python编码问题,因为好久用,所以很容易出现 # -*- c ...

  7. Java 调用http接口(基于OkHttp的Http工具类方法示例)

    目录 Java 调用http接口(基于OkHttp的Http工具类方法示例) OkHttp3 MAVEN依赖 Http get操作示例 Http Post操作示例 Http 超时控制 工具类示例 Ja ...

  8. (二)通过JAVA调用SAP接口 (增加一二级参数)

    (二)通过JAVA调用SAP接口 (增加一二级参数) 一.建立sap连接 请参考我的上一篇博客 JAVA连接SAP 二.测试项目环境准备 在上一篇操作下已经建好的环境后,在上面的基础上新增类即可 三. ...

  9. Java方法通过RestTemplate调用restful接口

    背景:项目A需要在代码内部调用项目B的一个restful接口,该接口是POST方式,header中 Authorization为自定义内容,主要传输的内容封装在body中,所以使用到了RestTemp ...

随机推荐

  1. [leetcode]449. Serialize and Deserialize BST设计BST的编解码

    这道题学到了东西. /* 一开始想着中序遍历,但是解码的时候才发现,中序遍历并不能唯一得确定二叉树. 后来看了网上的答案,发现先序遍历是可以的,观察了一下,对于BST,先序遍历确实是可以 唯一得确定. ...

  2. Java学习日报7.7

    今天进一步学习了eclipse软件,遇到了几次程序运行不成功的问题,检查之后运行成功!明天继续学习程序逻辑控制!

  3. Spring Cloud Eureka 简单创建

    1.pom.xml 添加相关依赖 <dependency>     <groupId>org.springframework.cloud</groupId>    ...

  4. WebService的开发手段

    一.WebService的开发手段 目前有关webService的开发手段有2种 1.JDK开发(jdk必须是1.6及以上版本,因为jdk是在1.6版本中引入并支持webservice开发的); 2. ...

  5. 谈谈 Vue 模板和 JSX

    工具链 从学习曲线角度来讲,结合我个人体会,React 学习路线是比 Vue 陡峭的,这个和 JSX.Template 有关吗?当然有.在 React 中使用 JSX,众所周知, JSX 需要经过 T ...

  6. Apache的Mod_rewrite学习(RewriteRule重写规则的语法) 转

    RewriteRuleSyntax: RewriteRule Pattern Substitution [flags] 一条RewriteRule指令,定义一条重写规则,规则间的顺序非常重要.对Apa ...

  7. 九个最容易出错的 Hive sql 详解及使用注意事项

    阅读本文小建议:本文适合细嚼慢咽,不要一目十行,不然会错过很多有价值的细节. 文章首发于公众号:五分钟学大数据 前言 在进行数仓搭建和数据分析时最常用的就是 sql,其语法简洁明了,易于理解,目前大数 ...

  8. VMware 16.1虚拟机安装

    VMware 16.1创建虚拟机 1.1首先打开我们安装好的VMware点击创建新的虚拟机 典型为自动安装,接口位默认 自定义安装更自由,可以把按需求选择 VMware16版本,只能选择Worksta ...

  9. web网上书店总结(jsp+servlet)

    web网上书店总结 前端的首页.效果如下: 基本上按照页面有的内容对其实现功能.按照用户划分功能模块,有后台管理员和普通用户,登录的时候会判断账户的类别,例如0权限代表普通用户登录,1权限代表管理员登 ...

  10. 无限重置IDE过期时间插件 亲测可以使用

    相信破解过IDEA的小伙伴,都知道jetbrains-agent这个工具,没错,就是那个直接拖入到开发工具界面,一键搞定,so easy的破解工具!这个工具目前已经停止更新了,尽管还有很多小伙伴在使用 ...