client客户端接收服务器数据,并返回信息
int count = 0;
try {
// 获取本机的IP对象
InetAddress iad = InetAddress.getLocalHost();
// 创建一个套接字对象 10010端口号要和服务器一致
Socket socket = new Socket(iad.getHostAddress(), 10010);
// String url = "{'url':'http://localhost:8080/Servlet/login','param':'123','method':'GET'}";
// String url = "{'url':'http://58.221.197.178:7802/connect/token','param':'grant_type=client_credentials&client_id="+CLIENT_ID+"&client_secret="+CLIENT_SECRET+"','method':'POST'}";
// String url = "{'url':'http://58.221.197.178:7802/api/charge/thirdPart/bankBill/getbill','param':'user_no=55441023','method':'GET'}";
// String url = "{'url':'http://58.221.197.178:7802/api/charge/thirdPart/bankBill/getpayfile','param':'branch_code=55441023&operator_code=55441023','method':'GET'}";
// String url = "{'url':'http://58.221.197.178:7802/api/charge/thirdPart/bankBill/pay','param':'branch_code=55441023&operator_code=00011&serial_no=3323231&user_no=123123&amount1396546','method':'POST'}";
// String url = "{'url':'http://58.221.197.178:7802/api/charge/thirdPart/bankBill/getsignup','param':'user_no=55441023','method':'GET'}";
// String url = "{'url':'http://58.221.197.178:7802/api/charge/thirdPart/bankBill/signup','param':'branch_code=001&operator_code=002&user_no003&bank_account=004&bank_name=005','method':'POST'}";
// String url = "{'url':'http://58.221.197.178:7802/api/charge/thirdPart/bankBill/cancelsign','param':'branch_code=55441023&operator_code=00011&&user_no=123123&bank_account=004&bank_name=005','method':'POST'}";
// String url = "{'url':'http://58.221.197.178:7802/api/charge/thirdPart/bankBill/offsetbill','param':'branch_code=55441023&operator_code=00011®ion_serial_no=006','method':'POST'}";
String url = "{'url':'http://58.221.197.178:7802/api/charge/thirdPart/bankBill/getpayfile','param':'branch_code=55441023&operator_code=00011','method':'GET'}";
//返回文件流
// String url = "{'url':'http://58.221.197.178:7802/api/charge/thirdPart/bankBill/downloadfile','param':'branch_code=55441023&operator_code=00011&file_id=007','method':'GET'}";
// 向服务端发送消息
// 1、获取套接字对应输出流对象
OutputStream out = socket.getOutputStream();
// 2、发送到服务器端的信息
out.write(url.getBytes());
;
// 接收服务端的信息
InputStream in = socket.getInputStream();
// 定义存储容器的缓冲区
byte[] b = new byte[1024];
// 读入到缓冲区的具体大小
int len = in.read(b);
// b数组,从0开始 ,长度
String a = new String (b,0,len);
System.out.println("接收服务端数据为:" + a);
// 释放套接字对象
socket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
服务器接收客户端信息,并返回数据
public class Server {
// 限制时间
static String timeLimit = null;
// 本次token获取时间
static long milliSecond =0;
static long timestamp =0;
// 请求数
static int count = 0;
// 信息
static String info = null;
// 最新的token
static String access_token = null;
// 失效的token
static String refresh_token = null;
// 请求url的信息
static String data = null;
// MD5加密
static String sign = "";
public final static String CLIENT_ID = "chinabank";
// 授权应用的appSecret(平台分配)
public static final String CLIENT_SECRET = "1q2w3e*";
// 获取AccessToken 的Url
public static final String GET_ACCESSTOKEN_URL = "http://58.221.197.178:7802/connect/token";
public static void main(String[] args) {
Socket socket = null;
ServerSocket server = null;
try {
// 创建一个服务器端对象 ,监听10010客户端 端口
server = new ServerSocket(10010);
System.out.println("服务器已经启动");
while (true) {
// 监听10010端口是否有数据传输
socket = server.accept(); // 让服务器阻塞的状态 等待数据传输,有数据就唤醒
// 获取输入流 和 输出流对象
// 接收客户端的信息
InputStream in = socket.getInputStream();
byte[] b = new byte[1024];
int len = in.read(b);
// b数组,从0开始 ,长度
String mes = new String(b, 0, len);
System.out.println("客户端发送的信息:" + mes);
// 将数据转为json提取方法的值,进行判断
JSONObject urlJson = JSON.parseObject(mes);
String method = urlJson.getString("method");
String url = urlJson.getString("url");
Mothod mothod = new Mothod();
String expires_in = urlJson.getString("expires_in");
data = urlJson.getString("param");
System.out.println("data:"+data);
// 如果 是第一次请求
if (count == 0) {
System.out.println("客户端第一次请求");
count++;
if (method.equals("POST")) {
System.out.println(123);
// MD5加密 POST
String plain = data+ "×tamp="+milliSecond+"&key="+CLIENT_SECRET;
sign =MD5(plain);
System.out.println("签名值"+sign);
//info = Mothod1.Post(url,data);
info = mothod.Post(url, data);
// 获取 第一次获取token的时间(毫秒)
milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
System.out.println("第一次请求的毫秒数" + milliSecond);
// 发送信息到客户端
OutputStream out = socket.getOutputStream();
out.write(info.getBytes());
JSONObject json = JSON.parseObject(info);
// 获取限制时间
timeLimit = json.getString("expires_in");
// 获取token
access_token = json.getString("access_token");
System.out.println("时间限制" + timeLimit);
System.out.println("token:"+access_token);
}
if (method.equals("GET")) {
System.out.println(456);
timestamp = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
System.out.println("第一次请求的毫秒数" + timestamp);
// get请求的MD5加密
String dataSort = Mothod.sort(data);
// MD5加密 GET
String plain = dataSort ;
sign =MD5(plain);
System.out.println("签名值"+sign);
info =Mothod1.GET(url,data);
// info = mothod.GET(url+"×tamp="+timestamp+"&sign="+sign,data);
// 发送信息到客户端
OutputStream out = socket.getOutputStream();
out.write(info.getBytes());
}
} else {
count++;
System.out.println("第" + count + "次请求");
// 不是第一次请求,那么看token是否过期,过期的话重新发送请求
// 第二次请求的时间
Long millNow = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
// 第二次请求的秒时间戳
long timeNow = millNow / 1000;
// 第1次请求的秒时间戳
long timeBefore = milliSecond / 1000;
// 时间限制 String 转long
long limitTime = Long.parseLong(timeLimit);
// 如果超时,再次获取token
if (timeNow - timeBefore > limitTime) {
System.out.println("超时");
// 超时的话,上个token就是失效的token
refresh_token = access_token;
info = mothod.Post(url, "grant_type=client_credentials&client_id=" + CLIENT_ID + "&client_secret=" + CLIENT_SECRET + "");
// 发送信息到客户端
OutputStream out = socket.getOutputStream();
out.write(info.getBytes());
// 获取 本次获取token的时间(毫秒)
milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
System.out.println("本次请求的毫秒数" + milliSecond);
JSONObject json = JSON.parseObject(info);
// 获取限制时间
timeLimit = json.getString("expires_in");
// 获取token
access_token = json.getString("access_token");
System.out.println("时间限制" + timeLimit);
System.out.println("token:"+access_token);
} else {
// 如果不超时,就将第一次请求的返回给客户端
// 发送信息到客户端
System.out.println("不超时");
OutputStream out = socket.getOutputStream();
out.write(info.getBytes());
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if (server != null){
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
方法
post方法、
get方法、
35位MD5加密方法、
对参数进行ASCLL码排序的方法、
截取=之前的方法、
冒泡排序、
将字符串转位ASCLL方法、
判断字符串中是否有某个特殊字符的方法
public class Mothod {
public static String Post(String url, String param) {
String line = "";
String token = access_token;
try {
URL realUrl = new URL(url);
// 打开和url之间的链接
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
// 发送POST请求必须设置如下两行
// 允许写出
conn.setDoOutput(true);
// 允许读入
conn.setDoInput(true);
// 设置缓存,注意设置请求方法为post不能用缓存
// conn.setUseCaches(false);
// 头部中的Accept-Charset会告诉服务器你发送的参数使用的是什么编码。
// 如果你不需要发送任何的参数,可以不用写Accept-Charset,
// 如果你不想发送任何的头部信息,可以直接使用URL.openStream()方法
conn.setRequestProperty("accept", "/*");
// 设置连接的状态
conn.setRequestProperty("connection", "Keep-Alive");
// 设定 请求格式
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Authorization", "Bearer " + access_token + "");
// 设置编码语言
conn.setRequestProperty("Accept-Charset", "utf-8");
// 通过什么工具来请求的
conn.setRequestProperty(
"user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestMethod("POST");
conn.connect(); // 表示连接
// 获取HttpURLConnection对象的输出流
PrintWriter out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
out.close();
// 定义BufferedReader输入流来读取URL的响应内容
InputStreamReader inputStreamReader = new InputStreamReader(conn.getInputStream(), "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
line = bufferedReader.readLine();
System.out.println(line);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return line;
}
// GET方法
public static String GET(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("Authorization", "Bearer " + access_token + "");
connection.setRequestProperty(
"user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
// 32位MD5加密
public static String MD5(String inStr) {
System.out.println(inStr);
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (Exception e) {
System.out.println(e.toString());
e.printStackTrace();
return "";
}
char[] charArray = inStr.toCharArray();
byte[] byteArray = new byte[charArray.length];
for (int i = 0; i < charArray.length; i++) byteArray[i] = (byte) charArray[i];
byte[] md5Bytes = md5.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16) hexValue.append("0");
hexValue.append(Integer.toHexString(val));
}
System.out.println(hexValue.toString());
System.out.println("123");
return hexValue.toString();
}
// GET请求时的排序方法 根据参数的键进行ASCII码排序
public static String sort(String param) {
// 获取到param数据 “version=1.0&name=example&time=2020-7-20”
System.out.println("要加密的参数"+param);
// 1、根据&分成3块放入【】数组中
String[] arr1 = param.split("&");
List list = new ArrayList(arr1.length);
// 将String数组转字符串
// String str1 = String.join(",", arr1);
// System.out.println("将键值对拿出来"+str1);
// 放 = 截取的数组
int i;
int j;
for (i = 0; i < arr1.length; i++) {
/** 结果 version=1.0 name=example time=2020-7-20 */
System.out.println("键值对:" + arr1[i]);
// 截取=号之前的字符,因为每次遍历只有一个键值
String a = arr1[i].substring(0, arr1[i].indexOf("="));
list.add(a);
}
// list 转string数组
String[] toBeStored = (String[]) list.toArray(new String[list.size()]);
// 冒泡
for (i = 0; i < toBeStored.length - 1; i++) {
for (j = i + 1; j < toBeStored.length; j++) {
if (ascllNum(toBeStored[i]) > ascllNum(toBeStored[j])) {
String aa = toBeStored[i];
toBeStored[i] = toBeStored[j];
toBeStored[j] = aa;
String bb = arr1[i];
arr1[i] = arr1[j];
arr1[j] = bb;
}
}
}
for (String cc : toBeStored) {
System.out.println(cc);
}
for (String dd : arr1) {
System.out.println(dd);
}
String str4 = StringUtils.join(arr1, "&");
System.out.println(str4);
return str4;
}
// }
public static int ascllNum(String key){
// 将字符串 转为ASCLL码
int count = 0;
char[] chars = key.toCharArray();
for (int m = 0; m < chars.length; m++) {
count += (int) chars[m];
}
return count;
}
// 判断是否有&
public static boolean specialCharacters(String stb) {
String regEx = "[&]|\n|\r|\t";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(stb);
System.out.println(m.find());
return m.find();
}
}