全网整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:400-708-3566

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


# Restful接口调用方法  # java中httpclient封装post请求和get的请求实例  # Java http请求封装工具类代码实例  # Java HttpClient技术详解  # Java HttpClient-Restful工具各种请求高度封装提炼及总结  # 给大家  # 都是  # 希望能  # 几种  # 这篇  # 在一  # 都以  # 小编  # 大家多多  # 在实际  # void  # main  # JerseyService  # jerseyDemo  # rest  # getRandomResource  # addResource  # Exception  # args  # throws 


相关文章: 如何通过FTP服务器快速搭建网站?  重庆市网站制作公司,重庆招聘网站哪个好?  建站之星后台搭建步骤解析:模板选择与产品管理实操指南  建站主机选哪家性价比最高?  建站之星安装后如何配置SEO及设计样式?  建站之星客服服务时间及联系方式如何?  东莞专业网站制作公司有哪些,东莞招聘网站哪个好?  简单实现Android文件上传  七夕网站制作视频,七夕大促活动怎么报名?  如何快速搭建自助建站会员专属系统?  中山网站推广排名,中山信息港登录入口?  建站之星如何取消后台验证码生成?  建站之星IIS配置教程:代码生成技巧与站点搭建指南  广州网站制作公司哪家好一点,广州欧莱雅百库网络科技有限公司官网?  C++如何将C风格字符串(char*)转换为std::string?(代码示例)  免费网站制作模板下载,除了易企秀之外还有什么H5平台可以制作H5长页面,最好是免费的?  北京制作网站的公司,北京铁路集团官方网站?  如何快速生成橙子建站落地页链接?  建站主机核心功能解析:服务器选择与网站搭建流程指南  javascript基本数据类型及类型检测常用方法小结  建站之星后台密码遗忘或太弱?如何重置与强化?  Bpmn 2.0的XML文件怎么画流程图  如何通过宝塔面板实现本地网站访问?  高端建站如何打造兼具美学与转化的品牌官网?  网站设计制作公司地址,网站建设比较好的公司都有哪些?  东莞市网站制作公司有哪些,东莞找工作用什么网站好?  如何快速搭建高效WAP手机网站吸引移动用户?  已有域名能否直接搭建网站?  广州网站设计制作一条龙,广州巨网网络科技有限公司是干什么的?  如何在Golang中指定模块版本_使用go.mod控制版本号  用v-html解决Vue.js渲染中html标签不被解析的问题  子杰智能建站系统|零代码开发与AI生成SEO优化指南  建设网站制作价格,怎样建立自己的公司网站?  北京专业网站制作设计师招聘,北京白云观官方网站?  小视频制作网站有哪些,有什么看国内小视频的网站,求推荐?  如何快速重置建站主机并恢复默认配置?  台州网站建设制作公司,浙江手机无犯罪记录证明怎么开?  深圳网站制作案例,网页的相关名词有哪些?  早安海报制作网站推荐大全,企业早安海报怎么每天更换?  官网建站费用明细查询_企业建站套餐价格及收费标准指南  我的世界制作壁纸网站下载,手机怎么换我的世界壁纸?  Swift中switch语句区间和元组模式匹配  建站VPS能否同时实现高效与安全翻墙?  Avalonia如何实现跨窗口通信 Avalonia窗口间数据传递  建站之星伪静态规则如何设置?  如何在局域网内绑定自建网站域名?  如何用景安虚拟主机手机版绑定域名建站?  如何高效利用200m空间完成建站?  定制建站哪家更专业可靠?推荐榜单揭晓  建站之星代理费用多少?最新价格详情介绍 

您的项目需求

*请认真填写需求信息,我们会在24小时内与您取得联系。