1.使用intellij idea开发,gradle构建工程。webcollection模块就是接口所在项目模块,handleMessage类就是接口类。
2.接口项目模块的build.gradle配置文件内容如下:
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'war'
group = 'com.cloudcollection'
archivesBaseName = 'webcollection'
version = '0.1'
sourceCompatibility = 1.8
targetCompatibility = 1.8
// java编译的时候缺省状态下会因为中文字符而失败
[compileJava,compileTestJava,javadoc]*.options*.encoding = 'UTF-8'
webAppDirName = 'webapp'
war{
archiveName ="webcollection.war"
}
buildscript {
repositories {
maven { url "https://repo.spring.io/libs-release" }
jcenter()
}
}
task wrapper(type: Wrapper) {
gradleVersion = '3.5'
}
idea {
module {
downloadJavadoc = false
downloadSources = false
}
}
sourceSets {
main {
output.resourcesDir = "bin/classes"
}
}
repositories {
mavenCentral()
mavenCentral name: "erichseifert.de", artifactUrls: ["http://mvn.erichseifert.de/maven2"]
}
dependencies {
compile project(":commons")
compile project(":model")
testCompile('junit:junit:4.12')
compile 'org.springframework:spring-core:4.3.6.RELEASE'
compile 'org.springframework:spring-web:4.3.6.RELEASE'
compile 'org.springframework:spring-webmvc:4.3.6.RELEASE'
providedCompile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.1.0'
}
war {
from 'src/main/webapp' // adds a file-set to the root of the archive
}
3.web.xml的内容如下:
dispatcher
org.springframework.web.servlet.DispatcherServlet
dispatcher
/
4.接口依赖查找需要用到配置文件dispatcher-servlet.xml,内容如下:
5.一切就绪,开始服务端接口的开发:handleMessage.java类
@RestController
@RequestMapping("/repository")
public class handleMessage {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
public handleMessage() {}
/**
* 获得token接口
* @param json 不同系统的唯一标识,可以生成唯一token返回
* @return
*/
@ResponseBody
@RequestMapping(value="/getCollectTaskToken",method = RequestMethod.POST,
produces = "application/json;charset=UTF-8")
public String getCollectTaskToken(@RequestBody String json) {
JSONObject jsonObject = JSONObject.fromObject(json);
String key = jsonObject.getString("key");
String token = "";
String msg = "token生成成功!";
String response = "true";
try {
//先根据key从数据库表中查询,如果有则返回token; 如果没有则创建保存。
Document doc = Mongodb.getMongoDb().getDatabase(Constant.MONGO_DB_NAME).getCollection(Constant.WEB_COLLECTION_TOKEN)
.find(Filters.eq("key",key)).first();
if (doc!=null) {
token = doc.getString("token");
} else {
//根据key生成唯一token,并生成json返回
token = StringUtils.hash(key);
//将系统的标识key和对应的token保存到mongodb中
Mongodb.getMongoDb().getDatabase(Constant.MONGO_DB_NAME).getCollection(Constant.WEB_COLLECTION_TOKEN)
.insertOne(new Document("key",key).append("token",token));
}
} catch (Exception e) {
logger.error("系统生成token失败:", e);
msg = "token生成失败!";
response = "false";
}
return "{\"msg\":\""+msg+"\",\"response\":\""+response+"\",\"token\":\""+token+"\"}";
}
6.传递的参数是json字符串,接口处理返回也是json字符串。
7.使用gradle build命令打war包,在tomcat中部署。
8.客户端请求类:
public class TestWebCollection {
//post提交调用方法
public static String post(String uri, Map map) throws UnsupportedEncodingException {
//所有的参数都放在map中,然后转换成json字符串传递到接口中
String str = JSONObject.fromObject(map).toString();
System.out.println("json参数:"+str);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(new StringEntity(str, Charset.forName("utf-8")));
try {
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("http返回码:"+statusCode);
//如果返回状态是200,打印返回信息
if (statusCode==200) {
HttpEntity entity = response.getEntity();
String entityStr = EntityUtils.toString(entity);
System.out.println("客户端接收内容:"+entityStr);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws UnsupportedEncodingException {
Map map = new HashMap<>();
//接口1
map.put("key","IRR2_0");//有多少个参数,都可放在map中
post("http://localhost:8080/webcollection/repository/getCollectTaskToken", map);
}
}
客户端调用接口控制台日志内容如下:
json参数:{"key":"IRR2_0"}
http返回码:200
客户端接收内容:{"msg":"token生成成功!","response":"true","token":"d71161a15e23713aedc7cb4bd0438fc5"}
9.特别注意:项目在idea工具中使用关联的tomcat启动服务,接口的url是不需要项目名称的,如下:
"http://localhost:8080/repository/getCollectTaskToken"
而项目在tomcat中单独部署时,接口的url需要加上web项目名称“webcollection”,不然会报404。