由于在实际项目中碰到的restful服务,参数都以json为准。这里我获取的接口和传入的参数都是json字符串类型。发布restful服务可参照文章http://www.cnblogs.com/jave1ove/p/7277861.html,以下接口调用基于此服务。

基于发布的Restful服务,下面总结几种常用的调用方法。

(1)Jersey API

  1. package com.restful.client;
  2.  
  3. import com.fasterxml.jackson.core.JsonProcessingException;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import com.restful.entity.PersonEntity;
  6. import com.sun.jersey.api.client.Client;
  7. import com.sun.jersey.api.client.ClientResponse;
  8. import com.sun.jersey.api.client.WebResource;
  9.  
  10. import javax.ws.rs.core.MediaType;
  11.  
  12. /**
  13. * Created by XuHui on 2017/8/7.
  14. */
  15. public class JerseyClient {
  16. private static String REST_API = "http://localhost:8080/jerseyDemo/rest/JerseyService";
  17. public static void main(String[] args) throws Exception {
  18. getRandomResource();
  19. addResource();
  20. getAllResource();
  21. }
  22.  
  23. public static void getRandomResource() {
  24. Client client = Client.create();
  25. WebResource webResource = client.resource(REST_API + "/getRandomResource");
  26. ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).accept("application/json").get(ClientResponse.class);
  27. String str = response.getEntity(String.class);
  28. System.out.print("getRandomResource result is : " + str + "\n");
  29. }
  30.  
  31. public static void addResource() throws JsonProcessingException {
  32. Client client = Client.create();
  33. WebResource webResource = client.resource(REST_API + "/addResource/person");
  34. ObjectMapper mapper = new ObjectMapper();
  35. PersonEntity entity = new PersonEntity("NO2", "Joker", "http://");
  36. ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, mapper.writeValueAsString(entity));
  37. System.out.print("addResource result is : " + response.getEntity(String.class) + "\n");
  38. }
  39.  
  40. public static void getAllResource() {
  41. Client client = Client.create();
  42. WebResource webResource = client.resource(REST_API + "/getAllResource");
  43. ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).accept("application/json").get(ClientResponse.class);
  44. String str = response.getEntity(String.class);
  45. System.out.print("getAllResource result is : " + str + "\n");
  46. }
  47. }

结果:

getRandomResource result is : {"id":"NO1","name":"Joker","addr":"http:///"}
addResource result is : {"id":"NO2","name":"Joker","addr":"http://"}
getAllResource result is : [{"id":"NO2","name":"Joker","addr":"http://"}]

(2)HttpURLConnection

  1. package com.restful.client;
  2.  
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4. import com.restful.entity.PersonEntity;
  5.  
  6. import java.io.BufferedReader;
  7. import java.io.InputStreamReader;
  8. import java.io.OutputStream;
  9. import java.net.HttpURLConnection;
  10. import java.net.URL;
  11.  
  12. /**
  13. * Created by XuHui on 2017/8/7.
  14. */
  15. public class HttpURLClient {
  16. private static String REST_API = "http://localhost:8080/jerseyDemo/rest/JerseyService";
  17.  
  18. public static void main(String[] args) throws Exception {
  19. addResource();
  20. getAllResource();
  21. }
  22.  
  23. public static void addResource() throws Exception {
  24. ObjectMapper mapper = new ObjectMapper();
  25. URL url = new URL(REST_API + "/addResource/person");
  26. HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
  27. httpURLConnection.setDoOutput(true);
  28. httpURLConnection.setRequestMethod("POST");
  29. httpURLConnection.setRequestProperty("Accept", "application/json");
  30. httpURLConnection.setRequestProperty("Content-Type", "application/json");
  31. PersonEntity entity = new PersonEntity("NO2", "Joker", "http://");
  32. OutputStream outputStream = httpURLConnection.getOutputStream();
  33. outputStream.write(mapper.writeValueAsBytes(entity));
  34. outputStream.flush();
  35.  
  36. BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
  37. String output;
  38. System.out.print("addResource result is : ");
  39. while ((output = reader.readLine()) != null) {
  40. System.out.print(output);
  41. }
  42. System.out.print("\n");
  43. }
  44.  
  45. public static void getAllResource() throws Exception {
  46. URL url = new URL(REST_API + "/getAllResource");
  47. HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
  48. httpURLConnection.setRequestMethod("GET");
  49. httpURLConnection.setRequestProperty("Accept", "application/json");
  50. BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
  51. String output;
  52. System.out.print("getAllResource result is :");
  53. while ((output = reader.readLine()) != null) {
  54. System.out.print(output);
  55. }
  56. System.out.print("\n");
  57. }
  58.  
  59. }

结果:

  1. addResource result is : {"id":"NO2","name":"Joker","addr":"http://"}
  2. getAllResource result is :[{"id":"NO2","name":"Joker","addr":"http://"}]

(3)HttpClient

  1. package com.restful.client;
  2.  
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4. import com.restful.entity.PersonEntity;
  5. import org.apache.http.HttpResponse;
  6. import org.apache.http.client.HttpClient;
  7. import org.apache.http.client.methods.HttpGet;
  8. import org.apache.http.client.methods.HttpPost;
  9. import org.apache.http.entity.StringEntity;
  10. import org.apache.http.impl.client.DefaultHttpClient;
  11. import org.apache.http.util.EntityUtils;
  12.  
  13. /**
  14. * Created by XuHui on 2017/8/7.
  15. */
  16. public class RestfulHttpClient {
  17. private static String REST_API = "http://localhost:8080/jerseyDemo/rest/JerseyService";
  18.  
  19. public static void main(String[] args) throws Exception {
  20. addResource();
  21. getAllResource();
  22. }
  23.  
  24. public static void addResource() throws Exception {
  25. HttpClient httpClient = new DefaultHttpClient();
  26. PersonEntity entity = new PersonEntity("NO2", "Joker", "http://");
  27. ObjectMapper mapper = new ObjectMapper();
  28.  
  29. HttpPost request = new HttpPost(REST_API + "/addResource/person");
  30. request.setHeader("Content-Type", "application/json");
  31. request.setHeader("Accept", "application/json");
  32. StringEntity requestJson = new StringEntity(mapper.writeValueAsString(entity), "utf-8");
  33. requestJson.setContentType("application/json");
  34. request.setEntity(requestJson);
  35. HttpResponse response = httpClient.execute(request);
  36. String json = EntityUtils.toString(response.getEntity());
  37. System.out.print("addResource result is : " + json + "\n");
  38. }
  39.  
  40. public static void getAllResource() throws Exception {
  41. HttpClient httpClient = new DefaultHttpClient();
  42. HttpGet request = new HttpGet(REST_API + "/getAllResource");
  43. request.setHeader("Content-Type", "application/json");
  44. request.setHeader("Accept", "application/json");
  45. HttpResponse response = httpClient.execute(request);
  46. String json = EntityUtils.toString(response.getEntity());
  47. System.out.print("getAllResource result is : " + json + "\n");
  48. }
  49. }

结果:

  1. addResource result is : {"id":"NO2","name":"Joker","addr":"http://"}
  2. getAllResource result is : [{"id":"NO2","name":"Joker","addr":"http://"}]

maven:

  1. <dependency>
  2. <groupId>org.apache.httpcomponents</groupId>
  3. <artifactId>httpclient</artifactId>
  4. <version>4.1.2</version>
  5. </dependency>

(4)JAX-RS API

  1. package com.restful.client;
  2.  
  3. import com.restful.entity.PersonEntity;
  4.  
  5. import javax.ws.rs.client.Client;
  6. import javax.ws.rs.client.ClientBuilder;
  7. import javax.ws.rs.client.Entity;
  8. import javax.ws.rs.core.MediaType;
  9. import javax.ws.rs.core.Response;
  10. import java.io.IOException;
  11.  
  12. /**
  13. * Created by XuHui on 2017/7/27.
  14. */
  15. public class RestfulClient {
  16. private static String REST_API = "http://localhost:8080/jerseyDemo/rest/JerseyService";
  17. public static void main(String[] args) throws Exception {
  18. getRandomResource();
  19. addResource();
  20. getAllResource();
  21. }
  22.  
  23. public static void getRandomResource() throws IOException {
  24. Client client = ClientBuilder.newClient();
  25. client.property("Content-Type","xml");
  26. Response response = client.target(REST_API + "/getRandomResource").request().get();
  27. String str = response.readEntity(String.class);
  28. System.out.print("getRandomResource result is : " + str + "\n");
  29. }
  30.  
  31. public static void addResource() {
  32. Client client = ClientBuilder.newClient();
  33. PersonEntity entity = new PersonEntity("NO2", "Joker", "http://");
  34. Response response = client.target(REST_API + "/addResource/person").request().buildPost(Entity.entity(entity, MediaType.APPLICATION_JSON)).invoke();
  35. String str = response.readEntity(String.class);
  36. System.out.print("addResource result is : " + str + "\n");
  37. }
  38.  
  39. public static void getAllResource() throws IOException {
  40. Client client = ClientBuilder.newClient();
  41. client.property("Content-Type","xml");
  42. Response response = client.target(REST_API + "/getAllResource").request().get();
  43. String str = response.readEntity(String.class);
  44. System.out.print("getAllResource result is : " + str + "\n");
  45.  
  46. }
  47. }

结果:

  1. getRandomResource result is : {"id":"NO1","name":"Joker","addr":"http:///"}
  2. addResource result is : {"id":"NO2","name":"Joker","addr":"http://"}
  3. getAllResource result is : [{"id":"NO2","name":"Joker","addr":"http://"}]

(5)webClient

  1. package com.restful.client;
  2.  
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4. import com.restful.entity.PersonEntity;
  5. import org.apache.cxf.jaxrs.client.WebClient;
  6.  
  7. import javax.ws.rs.core.Response;
  8.  
  9. /**
  10. * Created by XuHui on 2017/8/7.
  11. */
  12. public class RestfulWebClient {
  13. private static String REST_API = "http://localhost:8080/jerseyDemo/rest/JerseyService";
  14. public static void main(String[] args) throws Exception {
  15. addResource();
  16. getAllResource();
  17. }
  18.  
  19. public static void addResource() throws Exception {
  20. ObjectMapper mapper = new ObjectMapper();
  21. WebClient client = WebClient.create(REST_API)
  22. .header("Content-Type", "application/json")
  23. .header("Accept", "application/json")
  24. .encoding("UTF-8")
  25. .acceptEncoding("UTF-8");
  26. PersonEntity entity = new PersonEntity("NO2", "Joker", "http://");
  27. Response response = client.path("/addResource/person").post(mapper.writeValueAsString(entity), Response.class);
  28. String json = response.readEntity(String.class);
  29. System.out.print("addResource result is : " + json + "\n");
  30. }
  31.  
  32. public static void getAllResource() {
  33. WebClient client = WebClient.create(REST_API)
  34. .header("Content-Type", "application/json")
  35. .header("Accept", "application/json")
  36. .encoding("UTF-8")
  37. .acceptEncoding("UTF-8");
  38. Response response = client.path("/getAllResource").get();
  39. String json = response.readEntity(String.class);
  40. System.out.print("getAllResource result is : " + json + "\n");
  41. }
  42. }

结果:

  1. addResource result is : {"id":"NO2","name":"Joker","addr":"http://"}
  2. getAllResource result is : [{"id":"NO2","name":"Joker","addr":"http://"}

maven:

  1. <dependency>
  2. <groupId>org.apache.cxf</groupId>
  3. <artifactId>cxf-bundle-jaxrs</artifactId>
  4. <version>2.7.0</version>
    </dependency>

注:该jar包引入和jersey包引入有冲突,不能在一个工程中同时引用。

Restful接口调用方法超详细总结的更多相关文章

  1. 原生sql实现restful接口调用

    index.php <?php include './Request.php';include './Response.php';//获取数据$data=Request::getRequest( ...

  2. Yii框架实现restful 接口调用,增删改查

    创建模块modules; 在main.php中配置文件:(1) (2)控制器层: namespace frontend\modules\v1\controllers;use frontend\modu ...

  3. Restful API接口调用的方法总结

    restful 接口调用的方法 https://www.cnblogs.com/taozhiye/p/6704659.html http://www.jb51.net/article/120589.h ...

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

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

  5. flask + nginx + uwsgi + ubuntu18.04部署python restful接口

    目录 参考链接 效果展示 一.准备工作 1.1 可运行的python demo: 1.2 更新系统环境 二.创建python虚拟环境 三.设置flask应用程序 四.配置uWSGI 五.设置系统启动 ...

  6. 基于MD5+RSA算法实现接口调用防扯皮级鉴权

    概述 最近项目中需要对第三方开发接口调用,考虑了一下,准备采用MD5+RSA算对请求数据进行签名,来达到请求鉴权,过滤非法请求的目标. 数字签名采用MD5+RSA算法实现.RSA私钥要严格保密并提供安 ...

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

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

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

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

  9. 前端调用后端的方法(基于restful接口的mvc架构)

    1.前端调用后台: 建议用你熟悉的一门服务端程序,例如ASP,PHP,JSP,C#这些都可以,然后把需要的数据从数据库中获得,回传给客户端浏览器(其实一般就是写到HTML中,或者生成XML文件)然后在 ...

随机推荐

  1. Linux 中最常用的目录及文件管理命令

    一.查看文件的命令 对于一个文本文件,在linux中有多种查看方式来获知文件内容,如直接显示整个文本内容.分页查看内容.或者只查看文件开头或末尾的部分内容.在linux可以用不同的命令来实现. 1. ...

  2. 在Linux与Windows上获取当前堆栈信息

    在编写稳定可靠的软件服务时经常用到输出堆栈信息,以便用户/开发者获取准确的运行信息.常用在日志输出,错误报告,异常检测. 在Linux有比较简便的函数获取堆栈信息: #include <stdi ...

  3. 如何自定义容器网络?- 每天5分钟玩转 Docker 容器技术(33)

    除了 none, host, bridge 这三个自动创建的网络,用户也可以根据业务需要创建 user-defined 网络. Docker 提供三种 user-defined 网络驱动:bridge ...

  4. centos yum 没有可用软件包 nginx。

    新装的centos7中没有nginx的镜像源 因为nginx位于第三方的yum源里面,而不在centos官方yum源里面 解决方案: 安装epel: 去epel官网: http://fedorapro ...

  5. jquery fadeIn用法

    $("#msgSpan").fadeIn("slow"); setTimeout('$("#msgSpan").hide("slo ...

  6. 用window的onload事件,窗体加载完毕的时候

    <script type="text/javascript"> //用window的onload事件,窗体加载完毕的时候 window.onload=function( ...

  7. mongodb取出最大值与最小值

    $res=self::aggregate([ ['$match'=>[ 'msg_id'=>1007, 'D'=>16, ]], ['$group'=>[ '_id'=> ...

  8. EntityFramework.Extended.Update.Ambiguous column name

    异常描述 c#代码 dbcontext.Table.Where(x => x.B > 0).Update( x => new Table() { A = x.B } )  抛出异常: ...

  9. alibaba druid 在springboot start autoconfig 下的bug

    alibaba druid 在springboot start autoconfig下的bug 标签(空格分隔):druid springboot start autoconfig 背景 发现.分析过 ...

  10. NewsDao

    package com.pb.news.dao; import java.util.Date;import java.util.List; import com.pb.news.entity.News ...