iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >基于Restful接口调用方法总结(超详细)
  • 890
分享到

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

restful接口调用 2023-05-31 08:05:38 890人浏览 安东尼
摘要

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

由于在实际项目中碰到的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;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"); }}

--结束END--

本文标题: 基于Restful接口调用方法总结(超详细)

本文链接: https://www.lsjlt.com/news/224343.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作