Http的Get请求Post请求写法(附带获取token)以及json转换为java实体类(解析Json数据为Java实体和Java数组的代码。)

Http的Get请求Post请求写法(附带获取token)

目前项目使用的是微服务,但是.net团队有需要调用javaAPI的地方,一部分javaWeb的项目也会有调用javaApi的时候,下边提供Http调用的代码以及,解析Json数据为Java实体和Java数组的代码。

access_token

urlstr ,user ,password 为获取token的链接,账号密码

	/**
     * 获取本地token 方法
     */
    public static String getToken() throws IOException {
    
    
        String urlstr = "https://xxx.xxxx.com.cn/oauth/token";
        String user = "xxx";
        String password = "xxxx";
        StringBuilder data = new StringBuilder();
        URL url = new URL(urlstr);
        // 打开和URL之间的连接
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("POST");//请求post方式
        con.setUseCaches(false); // Post请求不能使用缓存
        con.setDoInput(true);// 设置是否从HttpURLConnection输入,默认值为 true
        con.setDoOutput(true);// 设置是否使用HttpURLConnection进行输出,默认值为 false
        //设置header内的参数 connection.setRequestProperty("健, "值");
        String authString = user + ":" + password;
        byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
        String authStringEnc = new String(authEncBytes);
        con.setRequestProperty("Authorization", "Basic " + authStringEnc);
        //设置body内的参数,put到JSONObject中
        String lineStart = "--";
        String boundary = "FlPm4LpSXsE";    // 数据分隔符
        String lineEnd = "\r\n";
        con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        StringBuilder sb = new StringBuilder();
        sb.append(lineStart + boundary + lineEnd);
        sb.append("Content-Disposition: form-data; name=\"grant_type\"" + lineEnd);
        sb.append(lineEnd);
        sb.append("client_credentials" + lineEnd);
        sb.append(lineStart + boundary + lineEnd);
        sb.append("Content-Disposition: form-data; name=\"scope\"" + lineEnd);
        sb.append(lineEnd);
        sb.append("all" + lineEnd);
        String ss = "\r\n--" + boundary + "--\r\n";
        sb.append(ss);
        DataOutputStream output = new DataOutputStream(con.getOutputStream());
        try {
    
    
            output.write(sb.toString().getBytes("utf-8"), 0, sb.toString().getBytes("utf-8").length);// 发送表单字段数据
            output.flush();
            output.close();
        } catch (IOException e) {
    
    
            throw new RuntimeException(e);
        }
        // 获取服务端响应,通过输入流来读取URL的响应
        InputStream is = con.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        StringBuffer sbf = new StringBuffer();
        String strRead = null;
        while ((strRead = reader.readLine()) != null) {
    
    
            sbf.append(strRead);
            sbf.append("\r\n");
        }
        reader.close();
        // 关闭连接
        con.disconnect();
        // 打印读到的响应结果
        System.out.println("运行结束:" + sbf.toString());
        String obj = sbf.toString();
        JSONObject jo = JSON.parseObject(obj);
        String token = jo.getString("access_token");
        return token;
    }

Http的Get请求

public static String doGet(String httpUrl) throws IOException {
    
    

    //根据实际情况写入acces_token,大多数在headers,我的方式是query的方式,是直接显示在url上的(不推荐)
      //  String api = YXW_API.getYXW_API();
        //有参数
        if (httpUrl.contains("?")) {
    
    
            httpUrl = YXW_API + httpUrl + "&access_token=" + getToken();
        } else {
    
    
            httpUrl = YXW_API + httpUrl + "?access_token=" + getToken();
        }

        // System.out.println("请求地址为:"+httpUrl);
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null;// 返回结果字符串
        try {
    
    
            // 创建远程url连接对象
            URL url = new URL(httpUrl);
            // 通过远程url连接对象打开一个连接,强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接方式:get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间:15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取远程返回的数据时间:60000毫秒
            connection.setReadTimeout(60000);
            // 发送请求
            connection.connect();
            // 通过connection连接,获取输入流
            if (connection.getResponseCode() == 200) {
    
    
                is = connection.getInputStream();
                // 封装输入流is,并指定字符集
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                // 存放数据
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
    
    
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
    
    
            e.printStackTrace();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            // 关闭资源
            if (null != br) {
    
    
                try {
    
    
                    br.close();
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }
            }

            if (null != is) {
    
    
                try {
    
    
                    is.close();
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }
            }

            connection.disconnect();// 关闭远程连接
        }
        log.info("API接口GET请求地址为:{}", httpUrl);
        return result;
    }

Http的Post请求

 public static String doPost(String httpUrl, String param) {
    
    
        httpUrl = YXW_API + httpUrl;
        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;
        try {
    
    
            URL url = new URL(httpUrl);
            // 通过远程url连接对象打开连接
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接请求方式
            connection.setRequestMethod("POST");
            // 设置连接主机服务器超时时间:15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取主机服务器返回数据超时时间:60000毫秒
            connection.setReadTimeout(60000);
            // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
            connection.setDoOutput(true);
            // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
            connection.setDoInput(true);
            // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
            connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            // 通过连接对象获取一个输出流
            os = connection.getOutputStream();
            // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
            os.write(param.getBytes());
            int code = connection.getResponseCode();
            System.out.println(code);
            // 通过连接对象获取一个输入流,向远程读取
            if (code == 200) {
    
    

                is = connection.getInputStream();
                // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

                StringBuffer sbf = new StringBuffer();
                String temp = null;
                // 循环遍历一行一行读取数据
                while ((temp = br.readLine()) != null) {
    
    
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            } else {
    
    

                result = "返回错误。ResponseCode: " + code;
            }
        } catch (MalformedURLException e) {
    
    
            e.printStackTrace();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            // 关闭资源
            if (null != br) {
    
    
                try {
    
    
                    br.close();
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }
            }
            if (null != os) {
    
    
                try {
    
    
                    os.close();
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }
            }
            if (null != is) {
    
    
                try {
    
    
                    is.close();
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }
            }
            // 断开与远程地址url的连接
            connection.disconnect();
        }
        log.info("API接口POST请求地址为:{}", httpUrl);
        return result;
    }

json转换为java实体类(解析Json数据为Java实体和Java数组的代码。)

首先restful’形式的接口,一般会定义固定的返回方式,我的为code,data,msg

@Data
public class ResponseVO<T> {
    
    
    private int code;
    private String msg;
    private T data;
}

解析json为实体

     ResponseVO<DearLine> responseVO = null;
        try {
    
    
            String s = APIHelper.Get("xxxx/dxxxxxx/getxxxxxxInfo?xxId=" + id;
            JSONObject jsonObject = JSON.parseObject(s);
            responseVO = JSONObject.toJavaObject(jsonObject, ResponseVO.class);
            if (responseVO.getCode() == 0) {
    
    
                Object data = responseVO.getData();
                JSONObject jo1 = JSON.parseObject(data.toString());
                DearLine dearLine = JSONObject.toJavaObject(jo1, DearLine.class);
                record.setDearLine(dearLine);
            } else {
    
    
                throw new RuntimeException("获取xxxxx信息失败");
            }
        } catch (Exception e) {
    
    
            System.out.println(e.getMessage());
            log.error("获取xxxx信息 error:", e);
        }

解析json为List

    ResponseVO<List<xxxx>> responseVO = null;
    List<xxxx> listVos = new ArrayList<>();
        try {
    
    
            String s = APIHelper.Get("xxxx/xxxx/xxxx");
            JSONObject jsonObject = JSON.parseObject(s);
            responseVO = JSONObject.toJavaObject(jsonObject, ResponseVO.class);
            if (responseVO.getCode() == 0) {
    
    
                JSONArray jsonArray = jsonObject.getJSONArray("data");
                listVos = JSON.parseArray(jsonArray.toJSONString(), xxxx.class);
            } else {
    
    
                throw new RuntimeException("获取xxxx信息失败");
            }
        } catch (Exception e) {
    
    
            System.out.println(e.getMessage());
            log.error("获取xxxx信息 error:", e);
        }

复制使用即可,亲民好用

附上依赖

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.51</version>
        </dependency>

猜你喜欢

转载自blog.csdn.net/luck_sheng/article/details/125553829
今日推荐