1. 程式人生 > >三種方式實現遠端restful 介面呼叫

三種方式實現遠端restful 介面呼叫

1,基本介紹

Restful介面的呼叫,前端一般使用ajax呼叫,後端可以使用的方法比較多,

  本次介紹三種:

    1.HttpURLConnection實現

    2.HttpClient實現

    3.Spring的RestTemplate 
    

2,HttpURLConnection實現

  1. @Controller

  2. public class RestfulAction {

  3. @Autowired

  4. private UserService userService;

  5. // 修改

  6. @RequestMapping(value = "put/{param}", method = RequestMethod.PUT)

  7. public @ResponseBody String put(@PathVariable String param) {

  8. return "put:" + param;

  9. }

  10. // 新增

  11. @RequestMapping(value = "post/{param}", method = RequestMethod.POST)

  12. public @ResponseBody String post(@PathVariable String param,String id,String name) {

  13. System.out.println("id:"+id);

  14. System.out.println("name:"+name);

  15. return "post:" + param;

  16. }

  17. // 刪除

  18. @RequestMapping(value = "delete/{param}", method = RequestMethod.DELETE)

  19. public @ResponseBody String delete(@PathVariable String param) {

  20. return "delete:" + param;

  21. }

  22. // 查詢

  23. @RequestMapping(value = "get/{param}", method = RequestMethod.GET)

  24. public @ResponseBody String get(@PathVariable String param) {

  25. return "get:" + param;

  26. }

  27. // HttpURLConnection 方式呼叫Restful介面

  28. // 呼叫介面

  29. @RequestMapping(value = "dealCon/{param}")

  30. public @ResponseBody String dealCon(@PathVariable String param) {

  31. try {

  32. String url = "http://localhost:8080/tao-manager-web/";

  33. url+=(param+"/xxx");

  34. URL restServiceURL = new URL(url);

  35. HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL

  36. .openConnection();

  37. //param 輸入小寫,轉換成 GET POST DELETE PUT

  38. httpConnection.setRequestMethod(param.toUpperCase());

  39. // httpConnection.setRequestProperty("Accept", "application/json");

  40. if("post".equals(param)){

  41. //開啟輸出開關

  42. httpConnection.setDoOutput(true);

  43. // httpConnection.setDoInput(true);

  44. //傳遞引數

  45. String input = "&id="+ URLEncoder.encode("abc", "UTF-8");

  46. input+="&name="+ URLEncoder.encode("啊啊啊", "UTF-8");

  47. OutputStream outputStream = httpConnection.getOutputStream();

  48. outputStream.write(input.getBytes());

  49. outputStream.flush();

  50. }

  51. if (httpConnection.getResponseCode() != 200) {

  52. throw new RuntimeException(

  53. "HTTP GET Request Failed with Error code : "

  54. + httpConnection.getResponseCode());

  55. }

  56. BufferedReader responseBuffer = new BufferedReader(

  57. new InputStreamReader((httpConnection.getInputStream())));

  58. String output;

  59. System.out.println("Output from Server: \n");

  60. while ((output = responseBuffer.readLine()) != null) {

  61. System.out.println(output);

  62. }

  63. httpConnection.disconnect();

  64. } catch (MalformedURLException e) {

  65. e.printStackTrace();

  66. } catch (IOException e) {

  67. e.printStackTrace();

  68. }

  69. return "success";

  70. }

  71. }

    3.HttpClient實現

  72. package com.taozhiye.controller;

  73. import org.apache.http.HttpEntity;

  74. import org.apache.http.HttpResponse;

  75. import org.apache.http.NameValuePair;

  76. import org.apache.http.client.HttpClient;

  77. import org.apache.http.client.entity.UrlEncodedFormEntity;

  78. import org.apache.http.client.methods.HttpDelete;

  79. import org.apache.http.client.methods.HttpGet;

  80. import org.apache.http.client.methods.HttpPost;

  81. import org.apache.http.client.methods.HttpPut;

  82. import org.apache.http.impl.client.HttpClients;

  83. import org.apache.http.message.BasicNameValuePair;

  84. import org.springframework.beans.factory.annotation.Autowired;

  85. import org.springframework.stereotype.Controller;

  86. import org.springframework.web.bind.annotation.PathVariable;

  87. import org.springframework.web.bind.annotation.RequestMapping;

  88. import org.springframework.web.bind.annotation.RequestMethod;

  89. import org.springframework.web.bind.annotation.ResponseBody;

  90. import com.fasterxml.jackson.databind.ObjectMapper;

  91. import com.taozhiye.entity.User;

  92. import com.taozhiye.service.UserService;

  93. import java.io.BufferedReader;

  94. import java.io.IOException;

  95. import java.io.InputStreamReader;

  96. import java.io.OutputStream;

  97. import java.net.HttpURLConnection;

  98. import java.net.MalformedURLException;

  99. import java.net.URL;

  100. import java.net.URLEncoder;

  101. import java.util.ArrayList;

  102. import java.util.List;

  103. @Controller

  104. public class RestfulAction {

  105. @Autowired

  106. private UserService userService;

  107. // 修改

  108. @RequestMapping(value = "put/{param}", method = RequestMethod.PUT)

  109. public @ResponseBody String put(@PathVariable String param) {

  110. return "put:" + param;

  111. }

  112. // 新增

  113. @RequestMapping(value = "post/{param}", method = RequestMethod.POST)

  114. public @ResponseBody User post(@PathVariable String param,String id,String name) {

  115. User u = new User();

  116. System.out.println(id);

  117. System.out.println(name);

  118. u.setName(id);

  119. u.setPassword(name);

  120. u.setEmail(id);

  121. u.setUsername(name);

  122. return u;

  123. }

  124. // 刪除

  125. @RequestMapping(value = "delete/{param}", method = RequestMethod.DELETE)

  126. public @ResponseBody String delete(@PathVariable String param) {

  127. return "delete:" + param;

  128. }

  129. // 查詢

  130. @RequestMapping(value = "get/{param}", method = RequestMethod.GET)

  131. public @ResponseBody User get(@PathVariable String param) {

  132. User u = new User();

  133. u.setName(param);

  134. u.setPassword(param);

  135. u.setEmail(param);

  136. u.setUsername("愛愛啊");

  137. return u;

  138. }

  139. @RequestMapping(value = "dealCon2/{param}")

  140. public @ResponseBody User dealCon2(@PathVariable String param) {

  141. User user = null;

  142. try {

  143. HttpClient client = HttpClients.createDefault();

  144. if("get".equals(param)){

  145. HttpGet request = new HttpGet("http://localhost:8080/tao-manager-web/get/"

  146. +"啊啊啊");

  147. request.setHeader("Accept", "application/json");

  148. HttpResponse response = client.execute(request);

  149. HttpEntity entity = response.getEntity();

  150. ObjectMapper mapper = new ObjectMapper();

  151. user = mapper.readValue(entity.getContent(), User.class);

  152. }else if("post".equals(param)){

  153. HttpPost request2 = new HttpPost("http://localhost:8080/tao-manager-web/post/xxx");

  154. List<NameValuePair> nvps = new ArrayList<NameValuePair>();

  155. nvps.add(new BasicNameValuePair("id", "啊啊啊"));

  156. nvps.add(new BasicNameValuePair("name", "secret"));

  157. UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nvps, "GBK");

  158. request2.setEntity(formEntity);

  159. HttpResponse response2 = client.execute(request2);

  160. HttpEntity entity = response2.getEntity();

  161. ObjectMapper mapper = new ObjectMapper();

  162. user = mapper.readValue(entity.getContent(), User.class);

  163. }else if("delete".equals(param)){

  164. }else if("put".equals(param)){

  165. }

  166. } catch (Exception e) {

  167. e.printStackTrace();

  168. }

  169. return user;

  170. }

  171. }

    4.Spring的RestTemplate

    springmvc.xml增加

  172. <!-- 配置RestTemplate -->

  173. <!--Http client Factory -->

  174. <bean id="httpClientFactory"

  175. class="org.springframework.http.client.SimpleClientHttpRequestFactory">

  176. <property name="connectTimeout" value="10000" />

  177. <property name="readTimeout" value="10000" />

  178. </bean>

  179. <!--RestTemplate -->

  180. <bean id="restTemplate" class="org.springframework.web.client.RestTemplate">

  181. <constructor-arg ref="httpClientFactory" />

  182. </bean>

    controller

  183. @Controller

  184. public class RestTemplateAction {

  185. @Autowired

  186. private RestTemplate template;

  187. @RequestMapping("RestTem")

  188. public @ResponseBody User RestTem(String method) {

  189. User user = null;

  190. //查詢

  191. if ("get".equals(method)) {

  192. user = template.getForObject(

  193. "http://localhost:8080/tao-manager-web/get/{id}",

  194. User.class, "嗚嗚嗚嗚");

  195. //getForEntity與getForObject的區別是可以獲取返回值和狀態、頭等資訊

  196. ResponseEntity<User> re = template.

  197. getForEntity("http://localhost:8080/tao-manager-web/get/{id}",

  198. User.class, "嗚嗚嗚嗚");

  199. System.out.println(re.getStatusCode());

  200. System.out.println(re.getBody().getUsername());

  201. //新增

  202. } else if ("post".equals(method)) {

  203. HttpHeaders headers = new HttpHeaders();

  204. headers.add("X-Auth-Token", UUID.randomUUID().toString());

  205. MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<String, String>();

  206. postParameters.add("id", "啊啊啊");

  207. postParameters.add("name", "部版本");

  208. HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(

  209. postParameters, headers);

  210. user = template.postForObject(

  211. "http://localhost:8080/tao-manager-web/post/aaa", requestEntity,

  212. User.class);

  213. //刪除

  214. } else if ("delete".equals(method)) {

  215. template.delete("http://localhost:8080/tao-manager-web/delete/{id}","aaa");

  216. //修改

  217. } else if ("put".equals(method)) {

  218. template.put("http://localhost:8080/tao-manager-web/put/{id}",null,"bbb");

  219. }

  220. return user;

  221. }

  222. }