1.1 http接口签名验证
1) 将表数据MD5签名
格式要求:json内嵌套json对象,需要组成字符串,json内嵌数组,不需要排序,直接参数=值1&值2...&值n,如key=1&id=2&secret=88eereff8
注意:
①使用replace(“”,””)函数来截取到对应格式。
②根据表数据封装成json的时候,要按表格里面字段顺序来依次封装到json对象中,作用:方便别人理解。
③为了使json数据按照ASCLL码顺序排序,建议使用fastjson,它会帮助我们自动排序,其依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.23</version>
</dependency>
如果使用net.sf.json,其依赖要添加<classifier>jdk15</classifier>,JSON.parseObject,是将Json字符串转化为相应的对象;JSON.toJSONString则是将对象转化为Json字符串。完整依赖如下:
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
1.2 MD5加密16位或者32位代码如下:
/**
* 对字符串md5加密(小写+字母)
* @param str 传入要加密的字符串
* @return MD5加密后的字符串
*/
public static String getMD5(String str) {
String result = "";
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes());
byte b[] = md.digest();
int i;
StringBuffer buf = new StringBuffer("");
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if (i < 0)
i += 256;
if (i < 16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
// 32 位:result = buf.toString();
// 16 位
result = buf.toString().substring(8, 24);
} catch (NoSuchAlgorithmException e) {
System.out.println(e);
}
return result;
}
1.3 使用http模拟post请求,传递json数据
post请求的时候要把参数放在body里,如果把参数放在url后面拼接(<head/>里)相当于加了一个params,而放在body里面由key value对应传递参数
/**
* post请求
* @param url
* @param json
* @return JSONObject
*/
public static net.sf.json.JSONObject doPost(String url,JSONObject json){
// 使用帮助类HttpClients创建CloseableHttpClient对象.
CloseableHttpClient httpclient = HttpClients.createDefault();
// HTTP请求类型创建HttpPost实例
HttpPost post = new HttpPost(url);
net.sf.json.JSONObject response = null;
try {
// 把json内容放到body里面
StringEntity s = new StringEntity(json.toString());
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
// 对于POST请求,把请求体填充进HttpPost实体.
post.setEntity(s);
// 通过执行HttpPost请求获取CloseableHttpResponse实例 ,从CloseableHttpResponse实例中获取状态码,错误信息,以及响应页面等等.
HttpResponse res = httpclient.execute(post);
// int SC_OK = 200;
if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
// 通过HttpResponse接口的getEntity方法返回响应信息,并进行相应的处理
HttpEntity entity = res.getEntity();
// 返回json格式:
String result = EntityUtils.toString(res.getEntity());
response = net.sf.json.JSONObject.fromObject(result);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return response;
}
282




被折叠的 条评论
为什么被折叠?



