REST服务发布与调用
使用Spring Boot发布接口服务
rest-server 项目结构
package com.xiangshuai.service.rest;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/**
* 服务端
* 发布接口服务,供cxf,httpclient,微服务的feigns三种客户端调用测试
* @author lqx
* 文件在 E:\学习文档子目录压缩\框架\工作流引擎\Activiti6.0\window\复习步骤34- 的发布与调用,cxf,httpclient,微服务的feigns三种客户端调用方式\rest-server.jar
或 我的网盘\我的笔记\学习文档子目录压缩\框架\工作流引擎\Activiti6.0\window\复习步骤34- 的发布与调用,cxf,httpclient,微服务的feigns三种客户端调用方式\rest-server.jar
*
*
*/
@RestController
public class PersonController {
/* 会自动将对象 p转成json格式,如:{"id":10086,"name":"xiaoming"}
注解RequestMapping中produces属性可以设置返回数据的类型以及编码,可以是json或者xml:
@RequestMapping(value="/xxx",produces = {"application/json;charset=UTF-8"})
或
@RequestMapping(value="/xxx",produces = {"application/xml;charset=UTF-8"})
String org.springframework.http.MediaType.APPLICATION_JSON_VALUE : "application/json"
*/
@GetMapping(path = "/person/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public Person getPerson(@PathVariable Integer id) {
Person p = new Person();
p.setId(id);
p.setName("xiaoming");
return p;
}
}
1.CXF调用服务
- <dependency>
- <groupId>org.apache.cxf</groupId>
- <artifactId>cxf-core</artifactId>
- <version>3.1.10</version>
- </dependency>
- <dependency>
- <groupId>org.apache.cxf</groupId>
- <artifactId>cxf-rt-rs-client</artifactId>
- <version>3.1.10</version>
- </dependency>
cxf-client 项目结构
package com.xiangshuai.client.cxf;
import java.io.InputStream;
import javax.ws.rs.core.Response;
import org.apache.cxf.helpers.IOUtils;
import org.apache.cxf.jaxrs.client.WebClient;
/**
* @author lqx
* cxf客户端调用rest-server服务端的接口--get请求
* 文件在 E:\学习文档子目录压缩\框架\工作流引擎\Activiti6.0\window\复习步骤34- 的发布与调用,cxf,httpclient,微服务的feigns三种客户端调用方式\cxf-client.jar
或 我的网盘\我的笔记\学习文档子目录压缩\框架\工作流引擎\Activiti6.0\window\复习步骤34- 的发布与调用,cxf,httpclient,微服务的feigns三种客户端调用方式\cxf-client.jar
*
*/
public class CxfClient {
public static void main(String[] args) throws Exception {
// 创建WebClient
WebClient client = WebClient
.create("http://localhost:8080/person/2");//url为我们rest-server发布的接口
// 获取响应
Response response = client.get();
// 获取响应内容
InputStream ent = (InputStream) response.getEntity();
String content = IOUtils.readStringFromStream(ent);
// 输出字符串
System.out.println(content);//{"id":2,"name":"xiaoming"}
}
}
2. HttpClient调用服务
package com.xiangshui.http.util;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
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.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
* fastjson-1.2.47.jar--json,map互转的jar包 不buildpath也可以,这里用不到
* 数字化接收驳回接口工具类
* @author lqx
* httpclient 客户端--get,post 请求
*
* httpclient 客户端调用rest-server服务端的接口--get请求 方法为 fileSignedHttpclientGet
*
* E:\学习文档子目录压缩\框架\工作流引擎\Activiti6.0\window\复习步骤34- 的发布与调用,cxf,httpclient,微服务的feigns三种客户端调用方式\httpclient_test.jar
或 我的网盘\我的笔记\学习文档子目录压缩\框架\工作流引擎\Activiti6.0\window\复习步骤34- 的发布与调用,cxf,httpclient,微服务的feigns三种客户端调用方式\httpclient_test.jar
*
*
*/
public class DrSignUtil {
//测试的post请求接口的 url--测试的
public static String postTestUrl ="http://ip:duankou/framework/qsDaArchive";
// httpclient post请求--------------------------------------------》》》》》
/**
*
* @param m -- 弄成一个list 作为fileJson 的 value
* @return post需要的JSON格式的请求体
*/
public static String qsServiceJson(String loginUserName,Map<String, String> m)throws Exception{
JSONObject jsonObject = new JSONObject();
//JSONArray jsonArray = new JSONArray();
List<JSONObject> list=new ArrayList<JSONObject>();//JSONObject 在json-lib-2.2.2-jdk15.jar中
JSONObject ajObject = new JSONObject();
for (String key : m.keySet()) {
ajObject.put(key, m.get(key));
}
//ajList.add(mNew);
//jsonArray.put(ajObject);
list.add(ajObject);
jsonObject.put("fileJson", list.toString());//必须toString--- 弄成"fileJson:[{"mkey1":"mvalue1","mkey2":"mvalue2"}] --key:list{map}格式
jsonObject.put("type", "ssda");
jsonObject.put("count", "1");
jsonObject.put("username", loginUserName);
String jsonString = jsonObject.toString();
System.out.println(jsonString);
return jsonString; //{"fileJson":[{"mkey1":"mvalue1","mkey2":"mvalue2"}] ,"type":"ssda","count":"1","username":"loginUserName"}
}
public static String getUrl(String url){
return url+"replayId="+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
}
/**
* httpClient post请求
* @param qsStr :post请求的请求体 json格式
* @return
*/
public static String fileSigned(String qsStr) {
String url = null;
JSONObject response = null;
String resultState = "";
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(300 * 1000)
.setConnectTimeout(300 * 1000)
.build();
url = getUrl(postTestUrl);
HttpPost post = new HttpPost(url);
post.setConfig(requestConfig);
post.setHeader("Content-Type","application/json;charset=utf-8");
System.out.println(qsStr);
StringEntity postingString = new StringEntity(qsStr,"utf-8");
post.setEntity(postingString);
//lqx
long startTime = System.currentTimeMillis();
HttpResponse res = httpClient.execute(post);
long endTime = System.currentTimeMillis();
long qqdrsj=(endTime-startTime)/1000/60;
System.out.println("请求东软时间为:"+qqdrsj);
//lqx
if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = EntityUtils.toString(res.getEntity(),"utf-8");// 返回json格式:
System.out.println(result);//{"fileJson":[{"code":"1","ajid":"260120180301501167","info":"成功"}]}
boolean contains = result.contains("成功");
resultState=contains?"1":"2";
if(resultState.equals("1")){
resultState = "1";
}else if(resultState.equals("2")){
System.out.println("访问错误!错误类型"+response.get("errorMsg"));
}else if(resultState.equals("0")){
System.out.println("接口没有没有数据!");
}
}else{
System.out.println("访问接口失败,状态码"+res.getStatusLine().getStatusCode());
}
} catch (SocketTimeoutException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return resultState;
}
// httpclient post请求--------------------------------------------》》》》》
// 非httpClient get请求---------------------------------------------------------
/**
* httpClient get请求
* @return
* @throws Exception
*/
public static String testfileSignedGet() throws Exception{
String dcCUrl = getDCUrlByBDCUrl("", "", "", "", "", "", "", "");//带参url
String result = getDataFromUrl(dcCUrl);
JSONObject json = JSONObject.fromObject(result);//json:response 的 key:value结构
return result;
}
/**get 请求
* 请求目标 url接口获取数据
* @param urlStr
* @return 请求后的response数据
* @throws Exception
*/
public static String getDataFromUrl(String urlStr) throws Exception {
//请求的webservice的url
URL url = new URL(urlStr);
//创建http链接
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//设置请求的方法类型
httpURLConnection.setRequestMethod("GET");
//设置接受数据
httpURLConnection.setDoInput(true);
//接收数据
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedInputStream bis = new BufferedInputStream(inputStream);
//定义字节数组
byte[] b = new byte[1024];
//定义一个输出流存储接收到的数据
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//开始接收数据
int len = 0;
while (true) {
len = bis.read(b);
/* len = inputStreamReader.read(b);*/
if (len == -1) {
//数据读完
break;
}
byteArrayOutputStream.write(b, 0, len);
}
//从输出流中获取读取到数据(服务端返回的)
String response = new String (byteArrayOutputStream.toByteArray(),"utf-8");
System.out.println("---->"+response);
return response;
}
/**
* 获取带参的url
* @param url 不带参数的原url
* @return 带参的url
*/
public static String getDCUrlByBDCUrl(String tableName,String url,String access_token ,String pageNo,String pageSize,String sTime,String eTime,String FYDM) {
url += "access_token="+access_token+"&format=json" ;
url += isNull(pageNo)?"":"&pageNo="+pageNo;
url += isNull(pageSize)?"":"&pageSize="+pageSize;
if(tableName.equalsIgnoreCase("V_DAJK_SP_SZ_ZDGX")){
return url;
}
if(tableName.equalsIgnoreCase("V_DAJK_SP_GDMRPZ")){
if(!isNull(FYDM)){
url += "&filter=(FYDM%20eq%20('"+FYDM+"'))";
}
}else{
if(!isNull(sTime)||!isNull(eTime)||!isNull(FYDM)){
url += "&filter=";
}
url += isNull(sTime)?"":"(GXSJ%20ge%20('"+sTime+"'))";
if(!isNull(sTime)&&(!isNull(eTime)||!isNull(FYDM))){
url += "%20and%20";
}
url += isNull(eTime)?"":"(GXSJ%20le%20('"+eTime+"'))";
if((!isNull(sTime)||!isNull(eTime))&&!isNull(FYDM)&&!url.endsWith("and%20")){
url += "%20and%20";
}
url += isNull(FYDM)?"":"(FYDM%20eq%20('"+FYDM+"'))";
}
return url;
}
public static boolean isNull(String str) {
if(str==null||str.trim().equals("")||str.trim().equalsIgnoreCase("null")){
return true;
}
return false;
}
public static boolean isNull(Object obj) {
if(obj==null||obj.toString()==null||obj.toString().trim().equals("")||obj.toString().trim().equalsIgnoreCase("null")){
return true;
}
return false;
}
// 非httpClient get请求---------------------------------------------------------
// httpClient get请求》》》》》》》》》》》》》》》
public static String fileSignedHttpclientGet() {
String url = "http://localhost:8080/person/666"; //自己rest-server服务端发布的接口地址
JSONObject response = null;
String resultState = "";
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(300 * 1000)
.setConnectTimeout(300 * 1000)
.build();
// url = getUrl(getTestUrl);
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(requestConfig);
httpGet.setHeader("Content-Type","application/json;charset=utf-8");
//lqx
long startTime = System.currentTimeMillis();
HttpResponse res = httpClient.execute(httpGet);
long endTime = System.currentTimeMillis();
long qqdrsj=(endTime-startTime);
System.out.println("请求东软时间毫秒为:"+qqdrsj);
//lqx
if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = EntityUtils.toString(res.getEntity(),"utf-8");// 返回json格式:
System.out.println(result);//{"fileJson":[{"code":"1","ajid":"260120180301501167","info":"成功"}]}
}else{
System.out.println("访问接口失败,状态码"+res.getStatusLine().getStatusCode());
}
} catch (SocketTimeoutException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return resultState;
}
// httpClient get请求《《《《《《《《《《《《《《
public static void main(String[] args) throws HttpException, IOException {
/*String qsStr="test:test";
fileSigned(qsStr);*/
fileSignedHttpclientGet();//请求东软时间毫秒为:62 {"id":666,"name":"xiaoming"}
/*Map<String, String> map = new HashMap<String, String>();
map.put("FJM", "J88855555");
map.put("jsr", "噢噢噢");*/
/*Map<String, String> map = new HashMap<String, String>();
map.put("FJM", "J00000333");
map.put("jsr", "噢噢噢");
try {
String qsServiceJson = qsServiceJson("admin", map);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
}
3. 使用Feign
feign-client项目结构
package com.xiangshuai.client.feign;
import feign.Param;
import feign.RequestLine;
public interface PersonClient {
@RequestLine("GET /person/{id}")
Person getPerson(@Param("id") Integer id);
}
package com.xiangshuai.client.feign;
import feign.Feign;
import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder;
/**
* 微服务的feigns客户端调用rest-server服务端的接口--get请求
* @author lqx
*文件在 E:\学习文档子目录压缩\框架\工作流引擎\Activiti6.0\window\复习步骤34- 的发布与调用,cxf,httpclient,微服务的feigns三种客户端调用方式\feign-client.jar
或 我的网盘\我的笔记\学习文档子目录压缩\框架\工作流引擎\Activiti6.0\window\复习步骤34- 的发布与调用,cxf,httpclient,微服务的feigns三种客户端调用方式\feign-client.jar
*/
public class TestMain {
public static void main(String[] args) {
// 获取服务接口
PersonClient personClient = Feign.builder()
.decoder(new GsonDecoder())//解析格式--即服务端接口返回数据的格式 ,这里是JOSN--所以用 new GsonDecoder
.target(PersonClient.class, "http://localhost:8080/");
// 请求接口
Person p = personClient.getPerson(3);//PersonClient 将json自动再转回对象
System.out.println(p.getId() + "---" + p.getName());//3---xiaoming
}
}