基于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接口调用方法总结(超详细)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • Jersey实现Restful服务(实例讲解)

    jersey 是基于Java的一个轻量级RESTful风格的Web Services框架.以下我基于IDEA实现Restful完整Demo. 1.创建maven-web工程,后面就是正常的maven工程创建流程. 2.添加Jersey框架的maven文件. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

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

    由于在实际项目中碰到的restful服务,参数都以json为准.这里我获取的接口和传入的参数都是json字符串类型.发布restful服务可参照文章 Jersey实现Restful服务(实例讲解),以下接口调用基于此服务. 基于发布的Restful服务,下面总结几种常用的调用方法. (1)Jersey API package com.restful.client; import com.fasterxml.jackson.core.JsonProcessingException; import

  • Java Feign微服务接口调用方法详细讲解

    目录 Feign说明 引入依赖启动类开启客户端 Feign接口开发 编写容错类 在业务层调用Feign客户端接口 Feign的常用属性如下 Feign说明 Feign是一种声明式.模板化的HTTP客户端.在spring cloud中使用Feign,可以做到类似于普通的接口的请求调用,可以发现对应的服务的接口,进而直接调用对应服务中的接口. 引入依赖启动类开启客户端 首先需要引入依赖 <dependency> <groupId>org.springframework.cloud<

  • WebService 的简单封装接口调用方法

    此方法完成了简单WebService 的简单调用封装,实现了简单Webservice简单调用的统一操作,避免了每增加一个操作都必须增加一个接口方法 的囧状! /// <summary> /// 封装同一的接口调用方法 /// </summary> /// <param name="_strSql">传入的简单sql</param> /// <param name="_strConnNmae">连接数据库字符

  • C#实现快递api接口调用方法

    无平台限制,依赖于快递api网接口 ----------------实体类 [DataContract] public class SyncResponseEntity { public SyncResponseEntity() { } /// <summary> /// 需要查询的快递代号 /// </summary> [DataMember(Order = 0, Name = "id")] public string ID { get; set; } ///

  • android 触屏的震动响应接口调用方法

    调用native 方法来开启和关闭vibrator: native static void vibratorOn(long milliseconds); native static void vibratorOff(); 调用方法如下: VibratorService.vibratorOn()

  • PHP编写RESTful接口的方法

    这是一个轻量级框架,专为快速开发RESTful接口而设计.如果你和我一样,厌倦了使用传统的MVC框架编写微服务或者前后端分离的API接口,受不了为了一个简单接口而做的很多多余的coding(和CTRL-C/CTRL-V),那么,你肯定会喜欢这个框架! 先举个栗子 1.写个HelloWorld.php,放到框架指定的目录下(默认是和index.php同级的apis/目录) /** * @path("/hw") */ class HelloWorld { /** * @route({&qu

  • 微信公众号H5支付接口调用方法

    本文实例为大家分享了 微信内H5调用支付接口的具体代码,供大家参考,具体内容如下 官方文档地址 <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>微信公众号H5接口调用</title> <script src='./js/md5.js'></script> </head>

  • php微信高级接口调用方法(自定义菜单接口、客服接口、二维码)

    怎么调用微信高级接口 微信高级接口和微信普通接口的区别 后台服务器可以调用微信的接口与微信用户进行讯息的通信,这样的行为就是在调用微信的接口,这些接口是基础接口,你不需要任何付费行为或者身份认证行为就可以调用.但是有一些高级接口,你的微信公众号必须达到一定的权限如通过微信认证才能调用自定义菜单.微信支付等高级功能. 不过微信公众帐号的测试号系统可以应用这些高级接口(微信支付等涉及交易的接口除外). 微信高级接口的调用 微信高级接口的调用需要先调用一个token_access接口,只有先调用这个接

  • C#读写xml文件方法总结(超详细!)

    目录 C#写入xml文件 1.XmlDocument 2.DataSet对象里的值来生成XML文件 3.利用XmlSerializer来将类的属性值转换为XML文件的元素值. 示例:写入xml 1.创建xml文档 2 .增加节点 3 .修改节点: 4 .删除节点 c#读取xml文件 总结 C#写入xml文件 1.XmlDocument 1.我认为是最原始,最基本的一种:利用XmlDocument向一个XML文件里写节点,然后再利用XmlDocument保存文件.首先加载要写入的XML文件,但是如

  • java调用Restful接口的三种方法

    目录 1,基本介绍 2,HttpURLConnection实现 3.HttpClient实现 4.Spring的RestTemplate 1,基本介绍 Restful接口的调用,前端一般使用ajax调用,后端可以使用的方法比较多, 本次介绍三种: 1.HttpURLConnection实现 2.HttpClient实现 3.Spring的RestTemplate 2,HttpURLConnection实现 @Controller public class RestfulAction { @Aut

随机推荐