Restful接口调用方法超详细总结
由于在实际项目中碰到的restful服务,参数都以json为准。这里我获取的接口和传入的参数都是json字符串类型。发布restful服务可参照文章http://www.cnblogs.com/jave1ove/p/7277861.html,以下接口调用基于此服务。
基于发布的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接口调用方法超详细总结的更多相关文章
- 原生sql实现restful接口调用
index.php <?php include './Request.php';include './Response.php';//获取数据$data=Request::getRequest( ...
- Yii框架实现restful 接口调用,增删改查
创建模块modules; 在main.php中配置文件:(1) (2)控制器层: namespace frontend\modules\v1\controllers;use frontend\modu ...
- Restful API接口调用的方法总结
restful 接口调用的方法 https://www.cnblogs.com/taozhiye/p/6704659.html http://www.jb51.net/article/120589.h ...
- 三种方法实现java调用Restful接口
1,基本介绍 Restful接口的调用,前端一般使用ajax调用,后端可以使用的方法比较多, 本次介绍三种: 1.HttpURLConnection实现 2.HttpClient实现 3.Spring ...
- flask + nginx + uwsgi + ubuntu18.04部署python restful接口
目录 参考链接 效果展示 一.准备工作 1.1 可运行的python demo: 1.2 更新系统环境 二.创建python虚拟环境 三.设置flask应用程序 四.配置uWSGI 五.设置系统启动 ...
- 基于MD5+RSA算法实现接口调用防扯皮级鉴权
概述 最近项目中需要对第三方开发接口调用,考虑了一下,准备采用MD5+RSA算对请求数据进行签名,来达到请求鉴权,过滤非法请求的目标. 数字签名采用MD5+RSA算法实现.RSA私钥要严格保密并提供安 ...
- 三种方法实现调用Restful接口
1.基本介绍 Restful接口的调用,前端一般使用ajax调用,后端可以使用的方法比较多, 本次介绍三种: 1.HttpURLConnection实现 2.HttpClient实现 3.Spring ...
- Java方法通过RestTemplate调用restful接口
背景:项目A需要在代码内部调用项目B的一个restful接口,该接口是POST方式,header中 Authorization为自定义内容,主要传输的内容封装在body中,所以使用到了RestTemp ...
- 前端调用后端的方法(基于restful接口的mvc架构)
1.前端调用后台: 建议用你熟悉的一门服务端程序,例如ASP,PHP,JSP,C#这些都可以,然后把需要的数据从数据库中获得,回传给客户端浏览器(其实一般就是写到HTML中,或者生成XML文件)然后在 ...
随机推荐
- 跨域访问之JSONP
跨域 在平常的工作中常常会遇到A站点的需要访问B站点的资源. 这时就产生了跨域访问. 跨域是指从一个域名的网页去请求另一个域名的资源.浏览器遵循同源策略,不允许A站点的Javascript 读取B站点 ...
- 团队开发冲刺2-----2day
冲刺目标: 1.在第一阶段的基础上完成app内部界面设计. 2.逐步完成app内每一部分内容. 3.对app的实现进一步仔细钻研考虑. 4.对app每一部分内容模块化,分工在进一步明确. 5.设计好数 ...
- angular 4使用jquery 第三方插件库
用jBox插件为例子 1,npm install jBox --save 2,找到.angular-cli.json 增加 "../node_modules/jbox/Source/jBo ...
- 安装GPU版本的tensorflow填过的那些坑!---CUDA说再见!
那些坑,那些说不出的痛! --------回首安装的过程,真的是填了一个坑又出现了一坑的感觉.记录下了算是自己的笔记也能给需要的人提供一点帮助. 1 写在前面的话 其实在装GPU版本的tensorfl ...
- PeopleCode事件和方法只用于online界面不能用于组件接口(component interface)
在使用CI过程中,哪些方法是不能使用的.以下为PeopleBook解释的内容. 一.搜索框代码不执行:SearchInit, SearchSave, and RowSelect events 意味着使 ...
- windows 10 下使用 binwalk
刚接触CTF没什么经验,菜鸟一只很多题不会做,就在网上看大佬写的Write up.发现经常会用到一个小工具--binwalk.binwalk在kali系统里是一个自带的工具,但windows可没有.之 ...
- SpringMvc支持跨域访问,Spring跨域访问,SpringMvc @CrossOrigin 跨域
SpringMvc支持跨域访问,Spring跨域访问,SpringMvc @CrossOrigin 跨域 >>>>>>>>>>>> ...
- HDU 5527---Too Rich(贪心+搜索)
题目链接 Problem Description You are a rich person, and you think your wallet is too heavy and full now. ...
- effective java 第2章-创建和销毁对象 读书笔记
背景 去年就把这本javaer必读书--effective java中文版第二版 读完了,第一遍感觉比较肤浅,今年打算开始第二遍,顺便做一下笔记,后续会持续更新. 1.考虑用静态工厂方法替代构造器 优 ...
- nopCommerce 3.9 大波浪系列 之 网页加载Widgets插件原理
一.插件简介 插件用于扩展nopCommerce的功能.nopCommerce有几种类型的插件如:支付.税率.配送方式.小部件等(接口如下图),更多插件可以访问nopCommerce官网. 我们看下后 ...