基于Restful接口调用方法总结(超详细)

 更新时间:2017年08月08日 09:17:40   投稿:jingxian  
下面小编就为大家带来一篇基于Restful接口调用方法总结(超详细)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

由于在实际项目中碰到的restful服务,参数都以json为准。这里我获取的接口和传入的参数都是json字符串类型。发布restful服务可参照文章 Jersey实现Restful服务(实例讲解),以下接口调用基于此服务。

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

(1)Jersey API

package com.restful.client;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.restful.entity.PersonEntity;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

import javax.ws.rs.core.MediaType;

/**
 * Created by XuHui on 2017/8/7.
 */
public class JerseyClient {
 private static String REST_API = "http://localhost:8080/jerseyDemo/rest/JerseyService";
 public static void main(String[] args) throws Exception {
  getRandomResource();
  addResource();
  getAllResource();
 }

 public static void getRandomResource() {
  Client client = Client.create();
  WebResource webResource = client.resource(REST_API + "/getRandomResource");
  ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).accept("application/json").get(ClientResponse.class);
  String str = response.getEntity(String.class);
  System.out.print("getRandomResource result is : " + str + "\n");
 }

 public static void addResource() throws JsonProcessingException {
  Client client = Client.create();
  WebResource webResource = client.resource(REST_API + "/addResource/person");
  ObjectMapper mapper = new ObjectMapper();
  PersonEntity entity = new PersonEntity("NO2", "Joker", "http://");
  ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, mapper.writeValueAsString(entity));
  System.out.print("addResource result is : " + response.getEntity(String.class) + "\n");
 }

 public static void getAllResource() {
  Client client = Client.create();
  WebResource webResource = client.resource(REST_API + "/getAllResource");
  ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).accept("application/json").get(ClientResponse.class);
  String str = response.getEntity(String.class);
  System.out.print("getAllResource result is : " + str + "\n");
 }
}

结果:

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

package com.restful.client;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.restful.entity.PersonEntity;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by XuHui on 2017/8/7.
 */
public class HttpURLClient {
 private static String REST_API = "http://localhost:8080/jerseyDemo/rest/JerseyService";

 public static void main(String[] args) throws Exception {
  addResource();
  getAllResource();
 }

 public static void addResource() throws Exception {
  ObjectMapper mapper = new ObjectMapper();
  URL url = new URL(REST_API + "/addResource/person");
  HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
  httpURLConnection.setDoOutput(true);
  httpURLConnection.setRequestMethod("POST");
  httpURLConnection.setRequestProperty("Accept", "application/json");
  httpURLConnection.setRequestProperty("Content-Type", "application/json");
  PersonEntity entity = new PersonEntity("NO2", "Joker", "http://");
  OutputStream outputStream = httpURLConnection.getOutputStream();
  outputStream.write(mapper.writeValueAsBytes(entity));
  outputStream.flush();

  BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
  String output;
  System.out.print("addResource result is : ");
  while ((output = reader.readLine()) != null) {
   System.out.print(output);
  }
  System.out.print("\n");
 }

 public static void getAllResource() throws Exception {
  URL url = new URL(REST_API + "/getAllResource");
  HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
  httpURLConnection.setRequestMethod("GET");
  httpURLConnection.setRequestProperty("Accept", "application/json");
  BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
  String output;
  System.out.print("getAllResource result is :");
  while ((output = reader.readLine()) != null) {
   System.out.print(output);
  }
  System.out.print("\n");
 }

}

结果:

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

(3)HttpClient

package com.restful.client;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.restful.entity.PersonEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

/**
 * Created by XuHui on 2017/8/7.
 */
public class RestfulHttpClient {
 private static String REST_API = "http://localhost:8080/jerseyDemo/rest/JerseyService";

 public static void main(String[] args) throws Exception {
  addResource();
  getAllResource();
 }

 public static void addResource() throws Exception {
  HttpClient httpClient = new DefaultHttpClient();
  PersonEntity entity = new PersonEntity("NO2", "Joker", "http://");
  ObjectMapper mapper = new ObjectMapper();

  HttpPost request = new HttpPost(REST_API + "/addResource/person");
  request.setHeader("Content-Type", "application/json");
  request.setHeader("Accept", "application/json");
  StringEntity requestJson = new StringEntity(mapper.writeValueAsString(entity), "utf-8");
  requestJson.setContentType("application/json");
  request.setEntity(requestJson);
  HttpResponse response = httpClient.execute(request);
  String json = EntityUtils.toString(response.getEntity());
  System.out.print("addResource result is : " + json + "\n");
 }

 public static void getAllResource() throws Exception {
  HttpClient httpClient = new DefaultHttpClient();
  HttpGet request = new HttpGet(REST_API + "/getAllResource");
  request.setHeader("Content-Type", "application/json");
  request.setHeader("Accept", "application/json");
  HttpResponse response = httpClient.execute(request);
  String json = EntityUtils.toString(response.getEntity());
  System.out.print("getAllResource result is : " + json + "\n");
 }
}

结果:

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

maven:

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.1.2</version>
</dependency>

(4)JAX-RS API

package com.restful.client;

import com.restful.entity.PersonEntity;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;

/**
 * Created by XuHui on 2017/7/27.
 */
public class RestfulClient {
 private static String REST_API = "http://localhost:8080/jerseyDemo/rest/JerseyService";
 public static void main(String[] args) throws Exception {
  getRandomResource();
  addResource();
  getAllResource();
 }

 public static void getRandomResource() throws IOException {
  Client client = ClientBuilder.newClient();
  client.property("Content-Type","xml");
  Response response = client.target(REST_API + "/getRandomResource").request().get();
  String str = response.readEntity(String.class);
  System.out.print("getRandomResource result is : " + str + "\n");
 }

 public static void addResource() {
  Client client = ClientBuilder.newClient();
  PersonEntity entity = new PersonEntity("NO2", "Joker", "http://");
  Response response = client.target(REST_API + "/addResource/person").request().buildPost(Entity.entity(entity, MediaType.APPLICATION_JSON)).invoke();
  String str = response.readEntity(String.class);
  System.out.print("addResource result is : " + str + "\n");
 }

 public static void getAllResource() throws IOException {
  Client client = ClientBuilder.newClient();
  client.property("Content-Type","xml");
  Response response = client.target(REST_API + "/getAllResource").request().get();
  String str = response.readEntity(String.class);
  System.out.print("getAllResource result is : " + str + "\n");

 }
}

结果:

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://"}]

(5)webClient

package com.restful.client;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.restful.entity.PersonEntity;
import org.apache.cxf.jaxrs.client.WebClient;

import javax.ws.rs.core.Response;

/**
 * Created by XuHui on 2017/8/7.
 */
public class RestfulWebClient {
 private static String REST_API = "http://localhost:8080/jerseyDemo/rest/JerseyService";
 public static void main(String[] args) throws Exception {
  addResource();
  getAllResource();
 }

 public static void addResource() throws Exception {
  ObjectMapper mapper = new ObjectMapper();
  WebClient client = WebClient.create(REST_API)
    .header("Content-Type", "application/json")
    .header("Accept", "application/json")
    .encoding("UTF-8")
    .acceptEncoding("UTF-8");
  PersonEntity entity = new PersonEntity("NO2", "Joker", "http://");
  Response response = client.path("/addResource/person").post(mapper.writeValueAsString(entity), Response.class);
  String json = response.readEntity(String.class);
  System.out.print("addResource result is : " + json + "\n");
 }

 public static void getAllResource() {
  WebClient client = WebClient.create(REST_API)
    .header("Content-Type", "application/json")
    .header("Accept", "application/json")
    .encoding("UTF-8")
    .acceptEncoding("UTF-8");
  Response response = client.path("/getAllResource").get();
  String json = response.readEntity(String.class);
  System.out.print("getAllResource result is : " + json + "\n");
 }
}

结果:

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

maven:

<dependency>
  <groupId>org.apache.cxf</groupId>
  <artifactId>cxf-bundle-jaxrs</artifactId>
  <version>2.7.0</version>
</dependency>

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

以上这篇基于Restful接口调用方法总结(超详细)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • 聊聊SpringBoot自动装配的魔力

    聊聊SpringBoot自动装配的魔力

    这篇文章主要介绍了SpringBoot自动装配的魔力,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-11-11
  • 深入讲解Java中的流程控制与运算符

    深入讲解Java中的流程控制与运算符

    这篇文章主要介绍了Java中的流程控制与运算符,是Java入门学习中的基础知识,需要的朋友可以参考下
    2015-09-09
  • 详解ZXing-core生成二维码的方法并解析

    详解ZXing-core生成二维码的方法并解析

    本文给大家介绍ZXing-core生成二维码的方法并解析,主要用到goggle发布的jar来实现二维码功能,对此文感兴趣的朋友一起学习吧
    2016-05-05
  • SpringBoot实现接口数据的加解密功能

    SpringBoot实现接口数据的加解密功能

    这篇文章主要介绍了SpringBoot实现接口数据的加解密功能,对接口的加密解密操作主要有两种实现方式,文中给大家详细介绍,需要的朋友可以参考下
    2019-10-10
  • java long转String +Codeforces110A案例

    java long转String +Codeforces110A案例

    这篇文章主要介绍了java long转String +Codeforces110A案例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-09-09
  • 详解JAVA 设计模式之状态模式

    详解JAVA 设计模式之状态模式

    这篇文章主要介绍了JAVA 状态模式的的相关资料,文中讲解的非常细致,帮助大家更好的学习理解JAVA 设计模式,感兴趣的朋友可以了解下
    2020-06-06
  • JVM方法调用invokevirtual详解

    JVM方法调用invokevirtual详解

    JVM调用方法有五条指令,分别是invokestatic,invokespecial,invokevirtual,invokeinterface,invokedynamic,这篇文章主要说明invokevirtual方法的调用问题,本文通过实例代码给大家介绍的非常详细,需要的朋友参考下吧
    2022-03-03
  • Spring Boot 中starter的原理详析

    Spring Boot 中starter的原理详析

    这篇文章主要介绍了Spring Boot 中starter原理详析,文章围绕主题展开springboot的插件机制和starter原理相关资料,需要的小伙伴可以参考一下
    2022-06-06
  • 一文详解Spring Security的基本用法

    一文详解Spring Security的基本用法

    Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架, 提供了完善的认证机制和方法级的授权功能。本文将通过一个简单的案例了解一下Spring Security的基本用法,需要的可以参考一下
    2022-05-05
  • Java中@JSONField和@JsonProperty注解的用法及区别详解

    Java中@JSONField和@JsonProperty注解的用法及区别详解

    @JsonProperty和@JSONField注解都是为了解决obj转json字符串的时候,将java bean的属性名替换成目标属性名,下面这篇文章主要给大家介绍了关于Java中@JSONField和@JsonProperty注解的用法及区别的相关资料,需要的朋友可以参考下
    2024-06-06

最新评论