当前位置:   article > 正文

java如何写接口给别人调用_java 对外提供接口

java 对外提供接口

计算机语言分类有很多,如C、C++、C#、Java、Php、Python等等,她们有各自的特性及擅长的领域,但她们各自又不是全能的。在一个稍微大型一点的项目都会用到多种语言共同完成,那么这些编程语言如何进行通信呢。什么意思呢,就是比如说我Java写的一个方法,其他编程语言要怎么去调用呢?这就是本文要探讨的问题了。

一般来说,方法层面的编程语言通信用的是网络接口形式,只暴露出形参和结果供别人调用。接口一般分为接口定义者和接口调用者,定义者可以规定接收参数的类型及返回形式,而接口定义者则只能完全按照接口定义者规定的参数进行访问。就叫是我们所说的webService(网络服务)。

以前的做法是利用XML作接口格式定义,然后通过Http做通讯和请求,如大名鼎鼎的SOAP,其实现在也是的,只不过现在流行RestFul风格的Rest接口形式,但用的还是XML+HTTP,那这两者有啥区别呢?最大的区别就是SOAP返回的主要是XML格式,有时还需要附带一些辅助文件,而Rest则还可以返回JSON类型的字符串,减少了很多繁乱的XML标签。本文就以Java为例,用她写一个接口,并让其他人去调用,以此来简单展示接口调用是怎么样一个过程。

步骤:

1、本机装有Java JDK运行环境及编程IDE(如Myeclipse)

2、建立一个maven项目,用以下载jar包,项目结构如下:



3 pom.xml文件内容如下:

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3. <modelVersion>4.0.0</modelVersion>
  4. <groupId>ws</groupId>
  5. <artifactId>restful</artifactId>
  6. <packaging>war</packaging>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <name>restful-server</name>
  9. <url>http://maven.apache.org</url>
  10. <properties>
  11. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  12. <jersey.version>2.6</jersey.version>
  13. <jersey-spring.version>2.23.1</jersey-spring.version>
  14. <spring.version>4.2.7.RELEASE</spring.version>
  15. <servlet-api-version>3.1.0</servlet-api-version>
  16. <logback.version>1.1.1</logback.version>
  17. <jcloverslf4j.version>1.7.6</jcloverslf4j.version>
  18. </properties>
  19. <dependencies>
  20. <dependency>
  21. <groupId>junit</groupId>
  22. <artifactId>junit</artifactId>
  23. <version>3.8.1</version>
  24. <scope>test</scope>
  25. </dependency>
  26. <dependency>
  27. <groupId>org.glassfish.jersey.ext</groupId>
  28. <artifactId>jersey-spring3</artifactId>
  29. <version>${jersey-spring.version}</version>
  30. <exclusions>
  31. <exclusion>
  32. <groupId>org.springframework</groupId>
  33. <artifactId>spring-core</artifactId>
  34. </exclusion>
  35. <exclusion>
  36. <groupId>org.springframework</groupId>
  37. <artifactId>spring-web</artifactId>
  38. </exclusion>
  39. <exclusion>
  40. <groupId>org.springframework</groupId>
  41. <artifactId>spring-beans</artifactId>
  42. </exclusion>
  43. </exclusions>
  44. </dependency>
  45. <dependency>
  46. <groupId>org.glassfish.jersey.containers</groupId>
  47. <artifactId>jersey-container-servlet</artifactId>
  48. <version>${jersey-spring.version}</version>
  49. </dependency>
  50. <dependency>
  51. <groupId>org.glassfish.jersey.containers</groupId>
  52. <artifactId>jersey-container-servlet-core</artifactId>
  53. <version>${jersey-spring.version}</version>
  54. </dependency>
  55. <dependency>
  56. <groupId>org.glassfish.jersey.media</groupId>
  57. <artifactId>jersey-media-json-jackson</artifactId>
  58. <version>${jersey.version}</version>
  59. </dependency>
  60. <dependency>
  61. <groupId>org.glassfish.jersey.media</groupId>
  62. <artifactId>jersey-media-multipart</artifactId>
  63. <version>${jersey.version}</version>
  64. </dependency>
  65. <dependency>
  66. <groupId>org.glassfish.jersey.ext</groupId>
  67. <artifactId>jersey-entity-filtering</artifactId>
  68. <version>${jersey.version}</version>
  69. </dependency>
  70. <!-- Spring4.2 dependencies -->
  71. <dependency>
  72. <groupId>org.springframework</groupId>
  73. <artifactId>spring-core</artifactId>
  74. <version>${spring.version}</version>
  75. </dependency>
  76. <dependency>
  77. <groupId>org.springframework</groupId>
  78. <artifactId>spring-context</artifactId>
  79. <version>${spring.version}</version>
  80. </dependency>
  81. <dependency>
  82. <groupId>org.springframework</groupId>
  83. <artifactId>spring-web</artifactId>
  84. <version>${spring.version}</version>
  85. </dependency>
  86. <dependency>
  87. <groupId>org.springframework</groupId>
  88. <artifactId>spring-jdbc</artifactId>
  89. <version>${spring.version}</version>
  90. </dependency>
  91. <dependency>
  92. <groupId>org.springframework</groupId>
  93. <artifactId>spring-tx</artifactId>
  94. <version>${spring.version}</version>
  95. </dependency>
  96. <dependency>
  97. <groupId>org.springframework</groupId>
  98. <artifactId>spring-test</artifactId>
  99. <version>${spring.version}</version>
  100. <scope>test</scope>
  101. </dependency>
  102. <dependency>
  103. <groupId>javax.servlet</groupId>
  104. <artifactId>javax.servlet-api</artifactId>
  105. <version>${servlet-api-version}</version>
  106. <scope>provided</scope>
  107. </dependency>
  108. <!-- Logback dependencies -->
  109. <dependency>
  110. <groupId>ch.qos.logback</groupId>
  111. <artifactId>logback-classic</artifactId>
  112. <version>${logback.version}</version>
  113. </dependency>
  114. <dependency>
  115. <groupId>org.slf4j</groupId>
  116. <artifactId>jcl-over-slf4j</artifactId>
  117. <version>${jcloverslf4j.version}</version>
  118. </dependency>
  119. </dependencies>
  120. <build>
  121. <finalName>restful</finalName>
  122. </build>
  123. </project>

4 applicationContext.xml内容如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:tx="http://www.springframework.org/schema/tx"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
  8. <context:component-scan base-package="com.kendy.*"></context:component-scan>
  9. </beans>

5 web.xml则主要配置采用的容器、日志管理及拦截器,拦截器可以实现到达请求郑涛之前进行身份认证,踢除没有访问资格的请求,而rest项目一般是用Jersey容器。配置如下:(kendy只是我的英文名,你们可以自己定义路径)

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  3. <display-name></display-name>
  4. <context-param>
  5. <param-name>contextConfigLocation</param-name>
  6. <param-value>classpath:applicationContext.xml</param-value>
  7. </context-param>
  8. <listener>
  9. <listener-class>
  10. org.springframework.web.context.ContextLoaderListener
  11. </listener-class>
  12. </listener>
  13. <servlet>
  14. <servlet-name>jersey-serlvet</servlet-name>
  15. <servlet-class>
  16. org.glassfish.jersey.servlet.ServletContainer
  17. </servlet-class>
  18. <init-param>
  19. <param-name>javax.ws.rs.Application</param-name>
  20. <param-value>com.kendy.filter.RestJaxRsApplication</param-value>
  21. </init-param>
  22. <load-on-startup>1</load-on-startup>
  23. </servlet>
  24. <servlet-mapping>
  25. <servlet-name>jersey-serlvet</servlet-name>
  26. <url-pattern>/*</url-pattern>
  27. </servlet-mapping>
  28. </web-app>


6 拦截器如下:

  1. import java.io.IOException;
  2. import java.io.InputStream;
  3. import java.util.List;
  4. import java.util.Map.Entry;
  5. import javax.ws.rs.WebApplicationException;
  6. import javax.ws.rs.container.ContainerRequestContext;
  7. import javax.ws.rs.container.ContainerRequestFilter;
  8. import javax.ws.rs.core.MultivaluedMap;
  9. import javax.ws.rs.core.Response.Status;
  10. import javax.ws.rs.ext.Provider;
  11. /**
  12. * 拦截请求
  13. */
  14. @Provider
  15. public class MyFilter implements ContainerRequestFilter {
  16. @Override
  17. public void filter(ContainerRequestContext context) throws IOException {
  18. //打印出所有请求头
  19. MultivaluedMap<String, String> map = context.getHeaders();
  20. for(Entry<String, List<String>> entry : map.entrySet()){
  21. String key = entry.getKey();
  22. List<String> valueList = entry.getValue();
  23. String values = valueList.toString();
  24. System.out.println(key + ":"+values.substring(1,values.length()-1));
  25. }

7 注册Jersey容器所要管理的类

  1. import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
  2. import org.glassfish.jersey.server.ResourceConfig;
  3. import com.kendy.restful.AccountManager;
  4. import com.kendy.restful.AuthorityManager;
  5. import com.kendy.restful.CardManager;
  6. import com.kendy.restful.DeviceManager;
  7. import com.kendy.restful.UserResource;
  8. /**
  9. * ${DESCRIPTION}
  10. */
  11. public class RestJaxRsApplication extends ResourceConfig {
  12. /**
  13. * Register JAX-RS application components.
  14. */
  15. public RestJaxRsApplication() {
  16. //服务类所在的包路径
  17. packages("com.kendy.*");
  18. // register application resources
  19. this.register(YouClass.class);
  20. // register filters
  21. this.register(MyFilter.class);
  22. //this.register(RequestContextFilter.class);
  23. register(JacksonJsonProvider.class);
  24. //register(MultiPartFeature.class);
  25. }
  26. }

8 接口定义(Restful风格)

  1. package com.kendy.restful;
  2. import java.text.SimpleDateFormat;
  3. import java.util.ArrayList;
  4. import java.util.Date;
  5. import java.util.HashMap;
  6. import java.util.List;
  7. import java.util.Map;
  8. import javax.ws.rs.Consumes;
  9. import javax.ws.rs.POST;
  10. import javax.ws.rs.Path;
  11. import javax.ws.rs.Produces;
  12. import javax.ws.rs.core.MediaType;
  13. import org.springframework.stereotype.Component;
  14. @Component
  15. @Path("/CardManager")
  16. public class CardManager {
  17. private SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  18. @POST
  19. @Path("size")
  20. @Consumes(MediaType.APPLICATION_JSON)
  21. @Produces(MediaType.APPLICATION_JSON)
  22. public Map<String,Object> size(){
  23. Map<String,Object> map = new HashMap<>();
  24. //do something here
  25. map.put("Size", 1024);
  26. return map;
  27. }
  28. @POST
  29. @Path("getDetail")
  30. @Consumes(MediaType.APPLICATION_JSON)
  31. @Produces(MediaType.APPLICATION_JSON)
  32. public Map<String,List<Map<String,Object>>> getDetail(){
  33. Map<String,List<Map<String,Object>>> map = new HashMap<>();
  34. //do something here
  35. List<Map<String,Object>> list = new ArrayList<>();
  36. Map<String,Object> subMap = new HashMap<>();
  37. subMap.put("UUID", 10086);
  38. subMap.put("CardID", 10081);
  39. subMap.put("StartTime", sdf.format(new Date()));
  40. subMap.put("EndTime", sdf.format(new Date()));
  41. list.add(subMap);
  42. map.put("Card", list);
  43. return map;
  44. }
  45. }

9 调用接口,有多种方式,本文用HttpClient

  1. /**
  2. * 发送 post请求webService接口
  3. * @param url 访问的接口地址
  4. * @param account 用户名
  5. * @param code 密码
  6. * @param param 查询参数
  7. * @return HttpResponse 该类包含请求方法的态码及返回的数据
  8. */
  9. public static HttpResponse post(String url,String account,String code,Map<String,Object> param) {
  10. //创建HttpClient实例及Post方法
  11. HttpClient httpclient = new DefaultHttpClient();
  12. HttpPost httppost = new HttpPost(url);
  13. //对用户密码MD5加密
  14. code = getMD5(code);
  15. //添加相关请求头,依情况而定
  16. httppost.setHeader("Authorization","WSSE profile=\"UsernameToken\"");
  17. httppost.setHeader("X-WSSE","UsernameToken Username=\""+account+"\",PasswordDigest=\""+code+"\"");
  18. httppost.addHeader("Content-type","application/json; charset=utf-8");
  19. httppost.setHeader("Accept", "application/json");
  20. httppost.setHeader("Connection","keep-alive");
  21. httppost.setHeader("Accept-Encoding","gzip");
  22. httppost.setHeader("Accept-Language", "zh-CN,en,*");
  23. httppost.setHeader("User-Agent","Mozilla/5.0");
  24. //传递请求参数
  25. String paramJsonStr = JSON.toJSONString(param);
  26. if(param != null)
  27. httppost.setEntity(new StringEntity(paramJsonStr, Charset.forName("UTF-8")));
  28. HttpResponse response = null;
  29. try {
  30. //执行post请求
  31. response = httpclient.execute(httppost);
  32. } catch (Exception e) {
  33. e.printStackTrace();
  34. }
  35. return response;
  36. }

10 返回接口



11 最后通过Map、List和Json工具对返回来的字面量进行各种处理。

  1. /**
  2. * 将从接口返回的JSON数据转换为实体集合等待插入数据表
  3. * 实体 IgmAccessControlChannelModel --> IGM_ACCESSCONTROL_CHANNEL
  4. * IgmStationDoorModel --> IGM_STATION_DOOR
  5. */
  6. @SuppressWarnings({ "unchecked", "rawtypes" })
  7. private Map<String,Object> getDeviceEntityList(String data){
  8. Map<String,Object> totalMap = new HashMap<>();
  9. //把以下三个结果放到totalMap里返回
  10. List<IgmAccessControlChannelModel> accessControlList = new ArrayList<>();
  11. List<IgmStationDoorModel> doorList = new ArrayList<>();
  12. List<String> deviceIds = new ArrayList<>();
  13. IgmAccessControlChannelModel accessControlModel = null;
  14. IgmStationDoorModel stationDoorModel = null;
  15. Map map = JSON.parseObject(data, Map.class);
  16. map = (Map<String,List<Map<String,Object>>>)map;
  17. List<Map<String,Object>> deviceList = (List<Map<String, Object>>) map.get("Device");
  18. for(Map<String,Object> deviceMap : deviceList){
  19. String deviceId = (String)(deviceMap.get("DeviceID")+"");
  20. Object channels = deviceMap.get("Channels");
  21. List<Map<String,Object>> channelList = (List<Map<String,Object>>)channels;
  22. String id = ""; //用于设置igmaccessControlchannel表和igmstationDoor表的stationDoorid
  23. //判断该门禁设备ID在本平台是否匹配
  24. boolean isMatched = isDeviceIdMatched(deviceId);
  25. if(isMatched){
  26. for(Map<String,Object> chnnelMap : channelList){
  27. accessControlModel = new IgmAccessControlChannelModel();
  28. stationDoorModel = new IgmStationDoorModel();
  29. for(Map.Entry<String, Object> entry : chnnelMap.entrySet()){
  30. String key = entry.getKey().trim();
  31. String value = "";
  32. if(key.equals("Channel")){
  33. value =(Integer)entry.getValue()+"";
  34. }else{
  35. value = (String)entry.getValue();
  36. }
  37. switch(key){
  38. case "Channel":
  39. accessControlModel.setCommandCode(Integer.parseInt(value));
  40. accessControlModel.setControlChannelName("控制通道"+value);
  41. stationDoorModel.setDoorCode(value);
  42. break;
  43. case "Description":
  44. stationDoorModel.setStationDoorName(value);
  45. break;
  46. default: break;
  47. }
  48. }
  49. id = UUID.randomUUID().toString();
  50. accessControlModel.setAccessControlChannelId(UUID.randomUUID().toString());
  51. accessControlModel.setDeviceId(deviceId);
  52. accessControlModel.setStationDoorId(id);
  53. stationDoorModel.setStationDoorId(id);
  54. stationDoorModel.setDeviceId(deviceId);
  55. stationDoorModel.setRemark("指纹门禁");
  56. accessControlList.add(accessControlModel);
  57. doorList.add(stationDoorModel);
  58. }
  59. deviceIds.add(deviceId);
  60. }else{
  61. //deviceId不匹配的跳过
  62. }
  63. }





声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/607984
推荐阅读
相关标签
  

闽ICP备14008679号