当前位置: 首页 > 编程笔记 >

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

岳晟
2023-03-14
本文向大家介绍基于Restful接口调用方法总结(超详细),包括了基于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接口调用方法总结(超详细)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持小牛知识库。

 类似资料:
  • 本文向大家介绍基于Require.js使用方法(总结),包括了基于Require.js使用方法(总结)的使用技巧和注意事项,需要的朋友参考一下 一、为什么要使用require.js 首先一个页面如果在加载多个js文件的时候,浏览器会停止网页渲染,加载文件越多,网页失去响应的时间就会越长;其次,由于js文件之间存在依赖关系,因此必须严格保证加载顺序,当依赖关系很复杂的时候,代码的编写和维护都会变得困

  • 本文向大家介绍总结C#动态调用WCF接口的两种方法,包括了总结C#动态调用WCF接口的两种方法的使用技巧和注意事项,需要的朋友参考一下 如何使用 1、第一种方式比较简单,而且也是大家喜欢的,因为不需要任何配置文件就可解决,只需知道服务契约接口和服务地址就可以调用。 2、使用Invoke的方式,但是需要在调用客户端配置WCF,配置后在Invoke类里封装服务契约接口即可。 客户端调用DEMO 第一种

  • 本文向大家介绍基于webpack 实用配置方法总结,包括了基于webpack 实用配置方法总结的使用技巧和注意事项,需要的朋友参考一下 1、webpack.config.js配置文件为: 2、package.json文件为: 3、命令行: 以上这篇基于webpack 实用配置方法总结就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持呐喊教程。

  • 本文向大家介绍Java 调用Restful API接口的几种方式(HTTPS),包括了Java 调用Restful API接口的几种方式(HTTPS)的使用技巧和注意事项,需要的朋友参考一下 摘要:最近有一个需求,为客户提供一些Restful API 接口,QA使用postman进行测试,但是postman的测试接口与java调用的相似但并不相同,于是想自己写一个程序去测试Restful API接

  • 本文向大家介绍详解PHP的抽象类和抽象方法以及接口总结,包括了详解PHP的抽象类和抽象方法以及接口总结的使用技巧和注意事项,需要的朋友参考一下 PHP中的抽象类和抽象方法自己用的不多,但是经常会在项目中看到别人使用,同样,今天在看别人的代码的时候,发现使用了抽象类,就总结下: 抽象类: 1、如果一个类中有一个方法是抽象方法,则这个类就是抽象类; 2、抽象类必须加上abstract关键字修饰; 抽象

  • 本文向大家介绍jquery学习总结(超级详细),包括了jquery学习总结(超级详细)的使用技巧和注意事项,需要的朋友参考一下 window.onload $(document).ready() 执行时机 必须等待网页中所有的内容加载完毕后(包括图片)才能执行 网页中所有DOM结构绘制完毕后就执行,可能DOM元素关联的东西并没有加载完 编写个数 不能同时编写多个,以下代码无法正确执行:window