由于在实际项目中碰到的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文档到电脑,方便收藏和打印~
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0