与其他系统接口对接(java),json格式数据传递···HttpURLConnection方式

这个操作是与****系统进行数据接口的对接,本系统向****系统传递几个参数,****系统接收并返回值。

目录

post请求方式

@Service层

工具类ResultUtil

pom需要添加的依赖

get请求方式

另一种 OkHttpClient 方式


post请求方式


@Service层

/*
*
* 预约结果查看
* 返回操作结果
* ResultUtil是单独封装的用来处理返回结果的一个工具类  根据自己的需求来实现吧
*     大体三个code msg data 错误error方法 和成功的  success方法
* */
//    OpinionApplyResultInfoParamPojo 你要传递的参数 单独建一个实体类 下面需要用到
    public Object getOpinionApplyResult(OpinionApplyResultInfoParamPojo oaripp) throws IOException {
        if(oaripp.equals(null)||oaripp==null){
            return ResultUtil.error(-1,"请求数据为空");
        }else if(oaripp.getVehicleNo().equals(null)||(oaripp.getVehicleNo().length()<7)||oaripp.getVehicleNo()==null){
            return ResultUtil.error(-1,"车牌号格式不正确");
        }
        String key = "123456";
        String user = "test";
//    你所需要的接口url
        String url = "http://services.sdyzgl.com/....1.0";
// paramValue 将要传的参数拼接起来。拼接规则 讲属性名按26字母的先后拼接 P在T的前面T在V的前面
        String paramValue = oaripp.getPlateColorCode() + oaripp.getTransCertificateCode() + oaripp.getVehicleNo();
        byte[] hmac = new HmacUtils(HmacAlgorithms.HMAC_SHA_1, key).hmac(paramValue);
        //将你要传递参数(直接将实体类放进去)进行json编码 变为json格式 
        String param = JSON.toJSONString(oaripp);
        String hmacZ = Hex.encodeHexString(hmac);
        param = param.substring(0, param.length() - 1) + ",\"userCode\":\"" + user + "\",\"hmac\":\"" + hmacZ + "\"}";//转义处理
        System.out.println(param + "----param");
        //与****系统交互,获取****信息交换接口
        URL restURL = new URL(url);
        PrintWriter out = null;//输出信息
        //打开和url之间的连接
        HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
        //请求方式
        conn.setRequestMethod("POST");
        // 设置通用的请求属性
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
        conn.setRequestProperty("Content-Type", "application/json");
        //设置是否向httpUrlConnection输出,设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个最常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,post与get的 不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
//  此处为post请求 故设为true 默认为 false
        conn.setDoOutput(true);
        conn.setDoInput(true);
        out = new PrintWriter(conn.getOutputStream());
        //发送请求参数即数据
        out.write(param);
        //缓冲数据
        out.flush();
        int code = conn.getResponseCode();
        System.out.println(code+"----code");

        InputStream is = null;
// ****系统返回信息  将返回信息封装为一个实体类 进行json解码,这里返回的是一组数据,所以使用list
        List<ApplyRuseltBakcMessagePojo> list = new ArrayList<>();
        if (code != 200) { // 非正常响应
            System.out.println("非正常响应");
            is = conn.getErrorStream();   //获取错误
            //构造一个字符流缓存
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            while ((str = br.readLine()) != null) {
                System.out.println(str + "-----------str");
//将****系统的返回值封装为单独的ErrorParamPojo实体类,进行json解码 获得****系统返回回来的值
//需要与****系统开发人员沟通
                ErrorParamPojo yze = JSON.parseObject(str, ErrorParamPojo.class);
                // 根据返回值进行返回提示信息
                if (yze != null) {
                    is.close();
                    conn.disconnect();
                    if ("100055".equals(yze.getErrorCode())) {
                        业务处理
                    } else if ("100042".equals(yze.getErrorCode())) {
                        业务处理
                    } else if ("100204".equals(yze.getErrorCode())) {
                        业务处理
                    }
                }
            }
        } else {
//正常响应操作
            is = conn.getInputStream();
            //构造一个字符流缓存
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            while ((str = br.readLine()) != null) {
                System.out.println(str+"----str");
//将返回值解码为json格式
                list = JSON.parseObject(str, ArrayList.class);
                System.out.println(list.toString()+"----list.tostring()");

                //关闭流
                is.close();
                //断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
                conn.disconnect();

                return ResultUtil.success(list);
            }
        }
        //关闭流
        is.close();
        //断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
        conn.disconnect();
        return ResultUtil.error(-1,"未知错误");
    }

 实体类、不用说。需要传啥或获取啥返回值就封装那些属性 get  set方法

工具类ResultUtil

public class ResultUtil {

    /** 执行成功 **/
    public  static Result success(Object object){
        Result result = new Result();
        result.setCode(0);
        result.setMsg("成功");
        result.setData(object);
        return result;
    }

    /** 执行成功  返回空对象 **/
    public  static  Result success(){
        return success(null);
    }

    /** 执行失败 **/
    public  static  Result error(Integer code,String msg){
        Result result = new Result();
        result.setCode(code);
        result.setMsg(msg);
        return result;
    }

}








public class Result<T> {
    /**  错误码  **/
    private Integer code;

    /**  提示信息 **/
    private String msg;

    /**  返回对象 具体内容 **/
    private T data;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

pom需要添加的依赖

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.12</version>
        </dependency>
        <!-- 以上为常用的spring boot所需要的依赖-->
        <!-- 以下为fastjson json对象处理所需要的依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency><!--commons codec-->
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.11</version>
        </dependency>
    </dependencies>

get请求方式

get方式则是直接将数据放到url后面

URL url = new URL("http://localhost:8080/Servlet/do_login.do?username=test&password=123456");

网上的一个例子

扫描二维码关注公众号,回复: 4050111 查看本文章

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * GET请求示例
 * 
 * @author 小明
 *
 */
public class GetDemo {

    public static void main(String[] args) {
        try {
            // 1. 得到访问地址的URL
            URL url = new URL(
                    "http://localhost:8080/Servlet/do_login.do?username=test&password=123456");
            // 2. 得到网络访问对象java.net.HttpURLConnection
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            /* 3. 设置请求参数(过期时间,输入、输出流、访问方式),以流的形式进行连接 */
            // 设置是否向HttpURLConnection输出
            connection.setDoOutput(false);
            // 设置是否从httpUrlConnection读入
            connection.setDoInput(true);
            // 设置请求方式
            connection.setRequestMethod("GET");
            // 设置是否使用缓存
            connection.setUseCaches(true);
            // 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
            connection.setInstanceFollowRedirects(true);
            // 设置超时时间
            connection.setConnectTimeout(3000);
            // 连接
            connection.connect();
            // 4. 得到响应状态码的返回值 responseCode
            int code = connection.getResponseCode();
            // 5. 如果返回值正常,数据在网络中是以流的形式得到服务端返回的数据
            String msg = "";
            if (code == 200) { // 正常响应
                // 从流中读取响应信息
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream()));
                String line = null;

                while ((line = reader.readLine()) != null) { // 循环从流中读取
                    msg += line + "\n";
                }
                reader.close(); // 关闭流
            }
            // 6. 断开连接,释放资源
            connection.disconnect();

            // 显示响应结果
            System.out.println(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这种方式在idea中启动服务一切正常。当使用tomcat部署项目时候,对方接口接收参数出现中文乱码问题。用了很多方式都没有解决,不知有没有大佬可以解决 ,代码中向****系统接口传参设置了 utf-8,tomcat 也设置了utf-8(server.xml 配置 这是配置的tomcat中文乱码)

点击   另一种 OkHttpClient 方式

猜你喜欢

转载自blog.csdn.net/qq_32786139/article/details/82867723