java調(diào)用Restful接口的三種方法
1,基本介紹
Restful接口的調(diào)用,前端一般使用ajax調(diào)用,后端可以使用的方法比較多,
本次介紹三種:
1.HttpURLConnection實(shí)現(xiàn)
2.HttpClient實(shí)現(xiàn)
3.Spring的RestTemplate
2,HttpURLConnection實(shí)現(xiàn)
@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 方式調(diào)用Restful接口 // 調(diào)用接口 @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 輸入小寫(xiě),轉(zhuǎn)換成 GET POST DELETE PUT httpConnection.setRequestMethod(param.toUpperCase()); // httpConnection.setRequestProperty("Accept", "application/json"); if("post".equals(param)){ //打開(kāi)輸出開(kāi)關(guān) httpConnection.setDoOutput(true); // httpConnection.setDoInput(true); //傳遞參數(shù) 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實(shí)現(xiàn)
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("愛(ài)愛(ài)啊"); 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的區(qū)別是可以獲取返回值和狀態(tài)、頭等信息 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; } }
到此這篇關(guān)于java調(diào)用Restful接口的三種方法的文章就介紹到這了,更多相關(guān)java調(diào)用Restful接口內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Java HttpClient-Restful工具各種請(qǐng)求高度封裝提煉及總結(jié)
- 一篇文章帶你搞懂Java restful 接口開(kāi)發(fā)
- Java Restful API的攔截詳解
- Java進(jìn)階之走進(jìn)RESTful接口
- java使用Feign實(shí)現(xiàn)聲明式Restful風(fēng)格調(diào)用
- Java 調(diào)用Restful API接口的幾種方式(HTTPS)
- 淺談java調(diào)用Restful API接口的方式
- 最好的8個(gè)Java RESTful框架
- Restful之通用返回格式類(lèi)設(shè)計(jì)
相關(guān)文章
java spring整合junit操作(有詳細(xì)的分析過(guò)程)
這篇文章主要介紹了java spring整合junit操作(有詳細(xì)的分析過(guò)程),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-08-08SpringCloud Eureka自我保護(hù)機(jī)制原理解析
這篇文章主要介紹了SpringCloud Eureka自我保護(hù)機(jī)制原理解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-02-02Effective Java 在工作中的應(yīng)用總結(jié)
《Effective Java》是一本經(jīng)典的 Java 學(xué)習(xí)寶典,值得每位 Java 開(kāi)發(fā)者閱讀。下面文章即是將書(shū)中和平日工作較密切的知識(shí)點(diǎn)做了部分總結(jié),需要的朋友可以參考下2021-09-09SpringBoot+Netty實(shí)現(xiàn)簡(jiǎn)單聊天室的示例代碼
這篇文章主要介紹了如何利用SpringBoot Netty實(shí)現(xiàn)簡(jiǎn)單聊天室,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)SpringBoot有一定幫助,感興趣的同學(xué)可以了解一下2022-02-02MyBatis圖文并茂講解注解開(kāi)發(fā)一對(duì)一查詢
這篇文章主要介紹了SpringBoot中Mybatis注解一對(duì)一查詢的實(shí)現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07Java實(shí)現(xiàn)動(dòng)態(tài)代理的實(shí)例代碼
代理模式是常用的java設(shè)計(jì)模式,他的特征是代理類(lèi)與委托類(lèi)有同樣的接口,代理類(lèi)主要負(fù)責(zé)為委托類(lèi)預(yù)處理消息、過(guò)濾消息、把消息轉(zhuǎn)發(fā)給委托類(lèi),以及事后處理消息等,這篇文章主要給大家介紹了關(guān)于Java實(shí)現(xiàn)動(dòng)態(tài)代理的相關(guān)資料,需要的朋友可以參考下2021-09-098個(gè)簡(jiǎn)單部分開(kāi)啟Java語(yǔ)言學(xué)習(xí)之路 附j(luò)ava學(xué)習(xí)書(shū)單
8個(gè)簡(jiǎn)單部分開(kāi)啟Java語(yǔ)言學(xué)習(xí)之路,附j(luò)ava學(xué)習(xí)書(shū)單,這篇文章主要向大家介紹了學(xué)習(xí)java語(yǔ)言的方向,感興趣的小伙伴們可以參考一下2016-09-09