springboot中使用socket对接第三方接口

1、接口对接需求如下

1.1 socket协议
1.2 报文中数据均是左对齐右补空格
1.3 报文编码采用:GBK
1.4 接口文档:
springboot中使用socket对接第三方接口

2、代码

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.util.List;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


public JSONObject testRequest(String userCode) throws IOException {
		logger.info("请求信息:{}",userCode);
		Socket socket = new Socket(ip, port);
		OutputStream os = socket.getOutputStream();
		byte[] param = byteMergerAll(
				fillParam("210", 3),//交易码
				fillParam(userCode, 10));//用户代码
		os.write(param);
		InputStream is = socket.getInputStream();
		byte[] result = new byte[1024];
		is.read(result);
		logger.info("响应信息:{},{}",new String(result, "GBK"));
		JSONObject resultJSON = new JSONObject();
		resultJSON.set("businessCode", new String(getByteByIndex(result, 0, 3)));//交易码
		resultJSON.set("code", new String(getByteByIndex(result, 4, 6)).trim());//响应码
		return resultJSON;
	}

3、涉及到的工具类

	/**
	 * 合并多个byte数组
	 *
	 * @param values
	 * @return
	 */
	private byte[] byteMergerAll(byte[]... values) {
		int length_byte = 0;
		for (int i = 0; i < values.length; i++) {
			length_byte += values[i].length;
		}
		byte[] all_byte = new byte[length_byte];
		int countLength = 0;
		for (int i = 0; i < values.length; i++) {
			byte[] b = values[i];
			System.arraycopy(b, 0, all_byte, countLength, b.length);
			countLength += b.length;
		}
		return all_byte;
	}

	/**
	 * 格式化参数
	 *
	 * @param str
	 * @param count
	 * @return
	 */
	private byte[] fillParam(String str, int count) throws UnsupportedEncodingException {
		if (str.getBytes("GBK").length >= count) {
			return str.getBytes("GBK");
		}
		byte[] data = str.getBytes("GBK");
		byte[] empty = new byte[count - data.length];
		for (int i = 0; i < empty.length; i++) {
			empty[i] = 32;
		}
		return byteMergerAll(empty, data);
	}
	
	/**
	 * 截取数组
	 *
	 * @param original
	 * @param begin
	 * @param end
	 * @return
	 */
	private byte[] getByteByIndex(byte[] original, int begin, int end) {
		byte[] result = new byte[end - begin + 1];
		int j = 0;
		for (int i = begin; i <= end; i++) {
			result[j] = original[i];
			j++;
		}
		return result;
	}

4、socket服务端本地测试工具

springboot中使用socket对接第三方接口
点击此处,下载socket工具

上一篇:JAVA网络编程


下一篇:HUST-计算机网络实验-socket编程