java 微信开发的工具类WeChatUtils

微信工具类需要的其他方法 

/**
 * 发送HttpPost请求
 *
 * @param strURL 服务地址
 * @param params json字符串,例如: "{ "id":"12345" }" ;其中属性名必须带双引号<br/>
 * @return 成功:返回json字符串<br/>
 */
public static Map<String, Object> reqPost(String strURL, String params) {
    BufferedReader reader;
    try {
        URL url = new URL(strURL);// 创建连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestMethod("POST"); // 设置请求方式
        connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
        connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
        connection.connect();
        //一定要用BufferedReader 来接收响应, 使用字节来接收响应的方法是接收不到内容的
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
        out.append(params);
        out.flush();
        out.close();
        // 读取响应
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        String line;
        String res = "";
        while ((line = reader.readLine()) != null) {
            res += line;
        }
        reader.close();

        return JSON.parseObject(res, Map.class);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

/**
 * 请求url
 *
 * @param url
 * @return
 */
public static Map<String, Object> reqGetMap(String url) {
    try {
        URL reqURL = new URL(url);
        HttpsURLConnection openConnection = (HttpsURLConnection) reqURL.openConnection();
        openConnection.setConnectTimeout(10000);
        //这里我感觉获取openid的时间比较长,不过也可能是我网络的问题,
        //所以设置的响应时间比较长
        openConnection.connect();
        InputStream in = openConnection.getInputStream();

        StringBuilder builder = new StringBuilder();
        BufferedReader bufreader = new BufferedReader(new InputStreamReader(in));
        for (String temp = bufreader.readLine(); temp != null; temp = bufreader
                .readLine()) {
            builder.append(temp);
        }

        String result = builder.toString();
        in.close();
        openConnection.disconnect();

        Map<String, Object> resultMap = JSON.parseObject(result, Map.class);

        return resultMap;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
经验分享 程序员 微信小程序 职场和发展