java调用Restful接口的三种方法
更新时间:2021年8月23日 00:00 点击:1455
1,基本介绍
Restful接口的调用,前端一般使用ajax调用,后端可以使用的方法比较多,
本次介绍三种:
1.HttpURLConnection实现
2.HttpClient实现
3.Spring的RestTemplate
2,HttpURLConnection实现
@Controller public class RestfulAction { @Autowired private UserService userService; // 修改 @RequestMapping(value = "put/{param}", method = RequestMethod.PUT) public @ResponseBody String put(@PathVariable String param) { return "put:" + param; } // 新增 @RequestMapping(value = "post/{param}", method = RequestMethod.POST) public @ResponseBody String post(@PathVariable String param,String id,String name) { System.out.println("id:"+id); System.out.println("name:"+name); return "post:" + param; } // 删除 @RequestMapping(value = "delete/{param}", method = RequestMethod.DELETE) public @ResponseBody String delete(@PathVariable String param) { return "delete:" + param; } // 查找 @RequestMapping(value = "get/{param}", method = RequestMethod.GET) public @ResponseBody String get(@PathVariable String param) { return "get:" + param; } // HttpURLConnection 方式调用Restful接口 // 调用接口 @RequestMapping(value = "dealCon/{param}") public @ResponseBody String dealCon(@PathVariable String param) { try { String url = "http://localhost:8080/tao-manager-web/"; url+=(param+"/xxx"); URL restServiceURL = new URL(url); HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL .openConnection(); //param 输入小写,转换成 GET POST DELETE PUT httpConnection.setRequestMethod(param.toUpperCase()); // httpConnection.setRequestProperty("Accept", "application/json"); if("post".equals(param)){ //打开输出开关 httpConnection.setDoOutput(true); // httpConnection.setDoInput(true); //传递参数 String input = "&id="+ URLEncoder.encode("abc", "UTF-8"); input+="&name="+ URLEncoder.encode("啊啊啊", "UTF-8"); OutputStream outputStream = httpConnection.getOutputStream(); outputStream.write(input.getBytes()); outputStream.flush(); } if (httpConnection.getResponseCode() != 200) { throw new RuntimeException( "HTTP GET Request Failed with Error code : " + httpConnection.getResponseCode()); } BufferedReader responseBuffer = new BufferedReader( new InputStreamReader((httpConnection.getInputStream()))); String output; System.out.println("Output from Server: \n"); while ((output = responseBuffer.readLine()) != null) { System.out.println(output); } httpConnection.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "success"; } }
3.HttpClient实现
package com.taozhiye.controller; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.fasterxml.jackson.databind.ObjectMapper; import com.taozhiye.entity.User; import com.taozhiye.service.UserService; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; @Controller public class RestfulAction { @Autowired private UserService userService; // 修改 @RequestMapping(value = "put/{param}", method = RequestMethod.PUT) public @ResponseBody String put(@PathVariable String param) { return "put:" + param; } // 新增 @RequestMapping(value = "post/{param}", method = RequestMethod.POST) public @ResponseBody User post(@PathVariable String param,String id,String name) { User u = new User(); System.out.println(id); System.out.println(name); u.setName(id); u.setPassword(name); u.setEmail(id); u.setUsername(name); return u; } // 删除 @RequestMapping(value = "delete/{param}", method = RequestMethod.DELETE) public @ResponseBody String delete(@PathVariable String param) { return "delete:" + param; } // 查找 @RequestMapping(value = "get/{param}", method = RequestMethod.GET) public @ResponseBody User get(@PathVariable String param) { User u = new User(); u.setName(param); u.setPassword(param); u.setEmail(param); u.setUsername("爱爱啊"); return u; } @RequestMapping(value = "dealCon2/{param}") public @ResponseBody User dealCon2(@PathVariable String param) { User user = null; try { HttpClient client = HttpClients.createDefault(); if("get".equals(param)){ HttpGet request = new HttpGet("http://localhost:8080/tao-manager-web/get/" +"啊啊啊"); request.setHeader("Accept", "application/json"); HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); ObjectMapper mapper = new ObjectMapper(); user = mapper.readValue(entity.getContent(), User.class); }else if("post".equals(param)){ HttpPost request2 = new HttpPost("http://localhost:8080/tao-manager-web/post/xxx"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("id", "啊啊啊")); nvps.add(new BasicNameValuePair("name", "secret")); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nvps, "GBK"); request2.setEntity(formEntity); HttpResponse response2 = client.execute(request2); HttpEntity entity = response2.getEntity(); ObjectMapper mapper = new ObjectMapper(); user = mapper.readValue(entity.getContent(), User.class); }else if("delete".equals(param)){ }else if("put".equals(param)){ } } catch (Exception e) { e.printStackTrace(); } return user; } }
4.Spring的RestTemplate
springmvc.xml增加
<!-- 配置RestTemplate --> <!--Http client Factory --> <bean id="httpClientFactory" class="org.springframework.http.client.SimpleClientHttpRequestFactory"> <property name="connectTimeout" value="10000" /> <property name="readTimeout" value="10000" /> </bean> <!--RestTemplate --> <bean id="restTemplate" class="org.springframework.web.client.RestTemplate"> <constructor-arg ref="httpClientFactory" /> </bean>
controller
@Controller public class RestTemplateAction { @Autowired private RestTemplate template; @RequestMapping("RestTem") public @ResponseBody User RestTem(String method) { User user = null; //查找 if ("get".equals(method)) { user = template.getForObject( "http://localhost:8080/tao-manager-web/get/{id}", User.class, "呜呜呜呜"); //getForEntity与getForObject的区别是可以获取返回值和状态、头等信息 ResponseEntity<User> re = template. getForEntity("http://localhost:8080/tao-manager-web/get/{id}", User.class, "呜呜呜呜"); System.out.println(re.getStatusCode()); System.out.println(re.getBody().getUsername()); //新增 } else if ("post".equals(method)) { HttpHeaders headers = new HttpHeaders(); headers.add("X-Auth-Token", UUID.randomUUID().toString()); MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<String, String>(); postParameters.add("id", "啊啊啊"); postParameters.add("name", "部版本"); HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>( postParameters, headers); user = template.postForObject( "http://localhost:8080/tao-manager-web/post/aaa", requestEntity, User.class); //删除 } else if ("delete".equals(method)) { template.delete("http://localhost:8080/tao-manager-web/delete/{id}","aaa"); //修改 } else if ("put".equals(method)) { template.put("http://localhost:8080/tao-manager-web/put/{id}",null,"bbb"); } return user; } }
到此这篇关于java调用Restful接口的三种方法的文章就介绍到这了,更多相关java调用Restful接口内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!
下一篇: JVM钩子函数的使用场景详解
相关文章
- 这篇文章主要介绍了如何利用java语言实现经典《复杂迷宫》游戏,文中采用了swing技术进行了界面化处理,感兴趣的小伙伴可以动手试一试...2022-02-01
java 运行报错has been compiled by a more recent version of the Java Runtime
java 运行报错has been compiled by a more recent version of the Java Runtime (class file version 54.0)...2021-04-01- 这篇文章主要介绍了在java中获取List集合中最大的日期时间操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-08-15
- 这篇文章主要介绍了Spring AOP 对象内部方法间的嵌套调用方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-08-29
- 这篇文章主要介绍了教你怎么用Java获取国家法定节假日,文中有非常详细的代码示例,对正在学习java的小伙伴们有非常好的帮助,需要的朋友可以参考下...2021-04-23
- <?php require('path.inc.php'); header('content-Type: text/html; charset=utf-8'); $borough_id = intval($_GET['id']); if(!$borough_id){ echo ' ...2016-11-25
- 这篇文章主要介绍了Java如何发起http请求的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-03-31
- 这篇文章主要介绍了c# 三种方法调用WebService接口的相关资料,文中示例代码非常详细,帮助大家更好的理解和学习,感兴趣的朋友可以了解下...2020-07-07
- 说起C#和Java这两门语言(语法,数据类型 等),个人以为,大概有90%以上的相似,甚至可以认为几乎一样。但是在工作中,我也发现了一些细微的差别...2020-06-25
- 这篇文章主要介绍了解决Java处理HTTP请求超时的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-29
- 这篇文章主要介绍了vue接口请求加密实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-08-12
- 这篇文章主要介绍了java 判断两个时间段是否重叠的案例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-08-15
- 这篇文章主要介绍了解决Vue watch里调用方法的坑,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-11-07
java 画pdf用itext调整表格宽度、自定义各个列宽的方法
这篇文章主要介绍了java 画pdf用itext调整表格宽度、自定义各个列宽的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-01-31- 这篇文章主要给大家介绍了关于c#中的WebService及其调用方式的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-06-25
- 这篇文章主要介绍了超简洁java实现双色球若干注随机号码生成(实例代码),本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-04-02
- 这篇文章主要介绍了js实现调用网络摄像头及常见错误处理,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-03-07
- 这篇文章主要介绍了Java生成随机姓名、性别和年龄的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-10-01
- 这篇文章介绍了c#动态调用Webservice的两种方法实例,有需要的朋友可以参考一下...2020-06-25
- 这篇文章主要介绍了解决vue watch数据的方法被调用了两次的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-11-07