微信支付V3-调用API接口(使用Get和Post请求)

文章目录

    • 证书
    • 统一下单
    • 订单查询
    • 优化post请求(使用cn.hutool.http.HttpUtil;)
    • 推荐使用Post请求

收藏好,1套视频搞定,支付宝&微信支付

证书

在这里插入图片描述

Get/Post请求微信API,以及sign加密

public class PayUtils {
   


    private final static String SERIAL_NO = "xxx";

    private final static String MCHID = "xxx";

    private static final String SCHEMA = "xxx";
// sendGet请求
    public static  String sendGet(String url,String sign) throws URISyntaxException {
   
        /** 获取连接客户端工具 **/
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String entityStr = null;
        CloseableHttpResponse response = null;
        try {
   

            /** 由于GET请求的参数都是拼装在URL地址后方,所以我们要构建一个URL,带参数 **/
            URIBuilder uriBuilder = new URIBuilder(url);

            /** 根据带参数的URI对象构建GET请求对象 **/
            HttpGet httpGet = new HttpGet(uriBuilder.build());

            /** 添加请求头信息 **/
            httpGet.addHeader("Accept", "application/json");
            httpGet.addHeader("Authorization", SCHEMA + " " + sign );
            /** 传输的类型 **/
            httpGet.addHeader("Content-Type", "application/json");

            /** 执行请求 **/
            response = httpClient.execute(httpGet);

            /** 获得响应的实体对象 **/
            HttpEntity entity = response.getEntity();
            entityStr = EntityUtils.toString(entity);
        } catch (IOException e) {
   
            e.printStackTrace();
        }
        return entityStr;
    }
// sendPost请求
    public static String sendPost(String url, String param, String sign) {
   

        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
   
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("Content-Type", "application/json");

//            conn.setRequestProperty("Charsert", "utf-8");
            conn.setRequestProperty("Authorization", SCHEMA + " " + sign);

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
   
                result += line;
            }
        } catch (Exception e) {
   
            System.out.println("发送 POST 请求出现异常!" + e);
            e.printStackTrace();
        }

你可能感兴趣的:(常见问题,post,get,微信支付)