public classTest {public static byte[] encrypt(String content, String password) {try{byte[] enCodeFormat =password.getBytes();
SecretKeySpec key= new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher= Cipher.getInstance("AES/ECB/PKCS5Padding");byte[] byteContent = content.getBytes("utf-8");
cipher.init(1, key);returncipher.doFinal(byteContent);
}catch(Exception e) {
e.printStackTrace();
}return null;
}public staticString jsonFormat(String resString){
StringBuffer jsonForMatStr= newStringBuffer();int level = 0;for(int index=0;index
{//获取s中的每个字符
char c =resString.charAt(index);//level大于0并且jsonForMatStr中的最后一个字符为\n,jsonForMatStr加入\t
if (level > 0 && '\n' == jsonForMatStr.charAt(jsonForMatStr.length() - 1)) {
jsonForMatStr.append(getLevelStr(level));
}//遇到"{"和"["要增加空格和换行,遇到"}"和"]"要减少空格,以对应,遇到","要换行
switch(c) {case '{':case '[':
jsonForMatStr.append(c+ "\n");
level++;break;case ',':
jsonForMatStr.append(c+ "\n");break;case '}':case ']':
jsonForMatStr.append("\n");
level--;
jsonForMatStr.append(getLevelStr(level));
jsonForMatStr.append(c);break;default:
jsonForMatStr.append(c);break;
}
}returnjsonForMatStr.toString();
}private static String getLevelStr(intlevel) {
StringBuffer levelStr= newStringBuffer();for (int levelI = 0; levelI < level; levelI++) {
levelStr.append("\t");
}returnlevelStr.toString();
}public staticString post(String url, String headers, String params){
System.out.println("请求地址:" +url);
System.out.println("请求参数:");
System.out.println(jsonFormat(params));//创建Httpclient对象
CloseableHttpClient httpClient =HttpClients.createDefault();
CloseableHttpResponse response= null;
String resultString= "";try{//创建Http Post请求
HttpPost httpPost = newHttpPost(url);//设置请求内容
httpPost.setEntity(newByteArrayEntity(params.getBytes()));//设置自定义请求头
if (!headers.isEmpty()) {
JSONObject jh=JSON.parseObject(headers);for(String h : jh.keySet()) {if (h.equals("Content-Type")) {
httpPost.addHeader(h, jh.getString(h));
}else{//设置公共请求头
httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
}
httpPost.addHeader(h, jh.getString(h));
}
}else{//设置公共请求头
httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
}//执行http请求
response =httpClient.execute(httpPost);//获取响应数据
if (response.getStatusLine().getStatusCode() == 200) {
resultString= EntityUtils.toString(response.getEntity());//返回json字符串格式:
}
System.out.println("响应参数:");
System.out.println(jsonFormat(resultString));
}catch(Exception e) {
e.printStackTrace();
}finally{try{
httpClient.close();
}catch(IOException e) {
e.printStackTrace();
}
}returnresultString;
}public static voidmain(String[] args) {
String data= "{\"amount\":64.39}";
String decrypt_data= new String(Base64.encodeBase64(encrypt(data, "xxxxx_PASSWORD")));
System.out.println(decrypt_data);
String params= String.format("{\"decrypt_data\":%s,\"data\":\"%s\"}",data, decrypt_data);
String url= "http://xxxxx/a/b/";
post(url,"", params);
}
}