Authored by fangyeqing

INIT:first commit

.idea
*.iml
target/
\ No newline at end of file
... ...
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.xkl</groupId>
<artifactId>xkl-web-example</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
... ...
package com.xkl;
/**
* Created by win7 on 2016/12/25.
*/
public interface Constants {
String URL_PREFIX = "http://127.0.0.1:8090";
//String URL_PREFIX = "https://139.129.166.85:8090";
String KEY = "weixin";
}
... ...
package com.xkl;
import java.security.MessageDigest;
/**
* Created by win7 on 2016/12/25.
*/
public class EncodeTools {
private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
'e', 'f' };
public static String encode(String algorithm, String str) {
if (str == null) {
return null;
}
try {
MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
messageDigest.update(str.getBytes());
return getFormattedText(messageDigest.digest());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Takes the raw bytes from the digest and formats them correct.
*
* @param bytes
* the raw bytes from the digest.
* @return the formatted bytes.
*/
private static String getFormattedText(byte[] bytes) {
int len = bytes.length;
StringBuilder buf = new StringBuilder(len * 2);
// 把密文转换成十六进制的字符串形式
for (int j = 0; j < len; j++) {
buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
}
return buf.toString();
}
}
... ...
package com.xkl;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;
/**
* Created by win7 on 2016/12/25.
*/
public class HttpTools {
/**
* 获取当前时间,10位
* @return
*/
public static String getNow(){
Calendar c = Calendar.getInstance();//可以对每个时间域单独修改
return String.valueOf(c.getTimeInMillis()/1000);
}
/**
* 获取签名
*
* 加密算法: sign=md5(str + t + key),32位小写md5
* t: 北京时间距离1970年1月1日的秒数,10位
* key:平台对应的key,此值喜开路管理员授予
* str:业务参数数组,按参数名递增排序排列拼接,例如用户登陆接口,coid+password+username
*
* 需要验证:
* sign:是否正确
* t:是否过期,客户端与服务器时间必须为±300s以内,否则时间验证过期。
* @param params
* @return
*/
public static String getSign(Map<String, String> params){
String sign = "";
String paramStr = "";
List<String> keys = new ArrayList<String>();
for(Map.Entry<String, String> entry : params.entrySet()) {
keys.add(entry.getKey());
}
Collections.sort(keys);
for(String para:keys){
if(!para.equals("sign")&&!para.equals("t")&&!para.equals("type"))
paramStr += params.get(para);
}
sign = EncodeTools.encode("MD5",paramStr + params.get("t") + Constants.KEY);
return sign;
}
/**
* 发送http请求
* @param url 请求url
* @param type 请求类型:GET,POST,DELETE
* @param params 请求参数:map类型
* @return
*/
public static String requestByMapWithToken(String url, String type, Map<String, String> params, String authorization){
String reqbody = getRequestData(params,"UTF-8").toString();
String result = requestByString(url + "?" + reqbody,type,authorization,null);
return result;
}
public static String requestByMap(String url, String type,Map<String, String> params){
return requestByMapWithToken(url,type,params,"");
}
/**
* 发送http请求
* @param url 请求url
* @param type 请求类型:GET,POST,DELETE
* @param reqbody 请求参数:String类型
* @return
*/
public static String requestByString(String url, String type, String authorization,String reqbody){
HttpURLConnection con = null;
String result = null;
try {
con = getHttpConnection( url , type, authorization);
//you can add any request body here if you want to post
if( reqbody != null){
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.writeBytes(reqbody);
out.flush();
out.close();
}
con.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String temp = null;
StringBuilder sb = new StringBuilder();
while((temp = in.readLine()) != null){
sb.append(temp).append(" ");
}
result = sb.toString();
in.close();
} catch (IOException e) {
System.out.println(e);
}
return result;
}
private static HttpURLConnection getHttpConnection(String url, String type, String authorization){
URL uri = null;
HttpURLConnection con = null;
try{
uri = new URL(url);
con = (HttpURLConnection) uri.openConnection();
con.setRequestMethod(type); //type: POST, PUT, DELETE, GET
if(type.equals("POST"))
con.setDoOutput(true);
con.setConnectTimeout(60000); //60 secs
con.setReadTimeout(60000); //60 secs
con.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
con.setRequestProperty("authorization",authorization);
}catch(Exception e){
System.out.println( "connection i/o failed" );
}
return con;
}
private static StringBuffer getRequestData(Map<String, String> params, String encode) {
StringBuffer stringBuffer = new StringBuffer(); //存储封装好的请求体信息
try {
for(Map.Entry<String, String> entry : params.entrySet()) {
stringBuffer.append(entry.getKey())
.append("=")
.append(URLEncoder.encode(entry.getValue(), encode))
.append("&");
}
stringBuffer.deleteCharAt(stringBuffer.length() - 1); //删除最后的一个"&"
} catch (Exception e) {
e.printStackTrace();
}
return stringBuffer;
}
}
... ...
package com.xkl;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
/**
* Created by win7 on 2017/1/2.
*/
public class OpenIdTest {
private static final String URL_OPEN_ID = Constants.URL_PREFIX + "/openId";
private static final String URL_LOGIN = Constants.URL_PREFIX + "/openId/login";
@Test
public void testBind(){
Map<String,String> params = new HashMap<String, String>();
params.put("username","user1");
params.put("password",EncodeTools.encode("MD5","pass1"));
params.put("openId","abcdefghijklmnopqrstuvwxyz123456");
params.put("openIdType","0");
params.put("t",HttpTools.getNow());
params.put("type","1");
params.put("sign",HttpTools.getSign(params));
String response = HttpTools.requestByMap(URL_OPEN_ID,"POST",params);
System.out.println(response);
}
@Test
public void testUnBind(){
Map<String,String> params = new HashMap<String, String>();
params.put("username","user1");
params.put("password",EncodeTools.encode("MD5","pass1"));
params.put("openId","abcdefghijklmnopqrstuvwxyz123456");
params.put("openIdType","0");
params.put("t",HttpTools.getNow());
params.put("type","1");
params.put("sign",HttpTools.getSign(params));
String response = HttpTools.requestByMap(URL_OPEN_ID,"DELETE",params);
System.out.println(response);
}
@Test
public void testLogin(){
Map<String,String> params = new HashMap<String, String>();
params.put("openId","abcdefghijklmnopqrstuvwxyz123456");
params.put("openIdType","0");
params.put("t",HttpTools.getNow());
params.put("type","1");
params.put("sign",HttpTools.getSign(params));
String response = HttpTools.requestByMap(URL_LOGIN,"POST",params);
System.out.println(response);
}
}
... ...
package com.xkl;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static com.xkl.TokenTest.loginAndGetToken;
/**
* Created by win7 on 2016/12/26.
* 报告相关
*/
public class ReportTest {
private static final String URL_REPORT_LIST = Constants.URL_PREFIX + "/report/list";
private static final String URL_REPORT_DETAIL = Constants.URL_PREFIX + "/report/detail";
private static final String URL_ITEM_INFO = Constants.URL_PREFIX + "/report/itemInfo";
private static final String URL_ITEM_GRAPH = Constants.URL_PREFIX + "/report/itemGraph";
private static String token;
@BeforeClass
public static void init(){
token = loginAndGetToken("user1","pass1");
}
@Test
public void testList(){
Map<String,String> params = new HashMap<String, String>();
params.put("t",HttpTools.getNow());
params.put("type","1");
params.put("sign",HttpTools.getSign(params));
String response = HttpTools.requestByMapWithToken(URL_REPORT_LIST,"GET",params,token);
System.out.println(response);
}
@Test
public void testDetail(){
Map<String,String> params = new HashMap<String, String>();
params.put("report_id","1");
params.put("t",HttpTools.getNow());
params.put("type","1");
params.put("sign",HttpTools.getSign(params));
String response = HttpTools.requestByMapWithToken(URL_REPORT_DETAIL,"GET",params,token);
System.out.println(response);
}
@Test
public void testItemInfo(){
Map<String,String> params = new HashMap<String, String>();
params.put("itemId","10");
params.put("status","0");
params.put("t",HttpTools.getNow());
params.put("type","1");
params.put("sign",HttpTools.getSign(params));
String response = HttpTools.requestByMapWithToken(URL_ITEM_INFO,"GET",params,token);
System.out.println(response);
}
@Test
public void testItemGraph(){
Map<String,String> params = new HashMap<String, String>();
params.put("itemId","10");
params.put("stime","2016-01-01 10:32:00");
params.put("etime","2016-12-22 10:32:00");
params.put("t",HttpTools.getNow());
params.put("type","1");
params.put("sign",HttpTools.getSign(params));
String response = HttpTools.requestByMapWithToken(URL_ITEM_GRAPH,"GET",params,token);
System.out.println(response);
}
}
\ No newline at end of file
... ...
package com.xkl;
import org.json.JSONObject;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
/**
* Created by win7 on 2017/1/2.
* 登录、退出登录测试
*/
public class TokenTest {
private static final String URL_LOGIN = Constants.URL_PREFIX + "/token";
public static String loginAndGetToken(String user,String pass){
Map<String,String> params = new HashMap<String, String>();
params.put("username",user);
params.put("password",EncodeTools.encode("MD5",pass));
params.put("t",HttpTools.getNow());
params.put("type","1");
params.put("sign",HttpTools.getSign(params));
String response = HttpTools.requestByMap(URL_LOGIN,"POST",params);
System.out.println("response:"+ response);
JSONObject jsonObject = new JSONObject(response);
JSONObject content = jsonObject.getJSONObject("content");
return content.getString("userId") + "_" + content.getString("token");
}
@Test
public void testLogin(){
System.out.println(loginAndGetToken("user1","pass1"));
}
@Test
public void logout(){
String token = loginAndGetToken("user1","pass1");
Map<String,String> params = new HashMap<String, String>();
params.put("t",HttpTools.getNow());
params.put("type","1");
params.put("sign",HttpTools.getSign(params));
String response = HttpTools.requestByMapWithToken(URL_LOGIN,"DELETE",params,token);
System.out.println(response);
}
}
... ...
package com.xkl;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static com.xkl.TokenTest.loginAndGetToken;
/**
* Created by win7 on 2016/12/25.
* 用户注册、修改密码、获取个人信息
*/
public class UserInfoTest {
private static final String URL_USER = Constants.URL_PREFIX + "/userInfo";
@Test
public void testRegister(){
register("15211112222","pass152");
}
@Test
public void testModPass(){
register("15211112222","pass152");
Map<String,String> params = new HashMap<String, String>();
params.put("password",EncodeTools.encode("MD5","pass152_new"));
params.put("t",HttpTools.getNow());
params.put("type","1");
params.put("sign",HttpTools.getSign(params));
//获取token
String token = loginAndGetToken("15211112222","pass152");
System.out.println(token);
String response = HttpTools.requestByMapWithToken(URL_USER,"PUT",params,token);
System.out.println(response);
}
@Test
public void testGetUserInfo(){
Map<String,String> params = new HashMap<String, String>();
params.put("t",HttpTools.getNow());
params.put("type","1");
params.put("sign",HttpTools.getSign(params));
//获取token
String token = loginAndGetToken("user1","pass1");
System.out.println(token);
String response = HttpTools.requestByMapWithToken(URL_USER,"GET",params,token);
System.out.println(response);
}
public void register(String user,String pass){
Map<String,String> params = new HashMap<String, String>();
params.put("username",user);
params.put("password",EncodeTools.encode("MD5",pass));
params.put("t",HttpTools.getNow());
params.put("type","1");
params.put("sign",HttpTools.getSign(params));
String response = HttpTools.requestByMap(URL_USER,"POST",params);
System.out.println(response);
}
@Test
public void testRegisterNoSign(){
Map<String,String> params = new HashMap<String, String>();
params.put("username","15211112222");
params.put("password",EncodeTools.encode("MD5","pass152"));
params.put("t",HttpTools.getNow());
params.put("type","1");
params.put("sign","nosign");
String response = HttpTools.requestByMap(URL_USER,"POST",params);
System.out.println(response);
}
@Test
public void testRegisterWrongTime(){
Map<String,String> params = new HashMap<String, String>();
params.put("username","15211112222");
params.put("password",EncodeTools.encode("MD5","pass152"));
params.put("t",HttpTools.getNow()+100000);
params.put("type","1");
params.put("sign",HttpTools.getSign(params));
String response = HttpTools.requestByMap(URL_USER,"POST",params);
System.out.println(response);
}
}
... ...