微信开发(二)http请求工具类

2023-05-16

说明

      进行微信开发,后台程序需要与微信服务器进行交互,通过调用接口来完成服务,阅读微信开发文档,发现接口的调用都是通过http请求进行的,所以必须有个HttpUtil来支撑,这里总结下以javaAPI的方式和以Apach的HttpClient的方式进行HTTP请求

正文

使用java的HttpURLConnection

一个方法实现GET,POST请求

public static String httpRequest(String requestUrl, String requestMethod, String outputStr){
        StringBuffer buffer = new StringBuffer();
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setRequestMethod(requestMethod);

            if("GET".equalsIgnoreCase(requestMethod)){
                httpURLConnection.connect();
            }

            if(null != outputStr){
                OutputStream outputStream = httpURLConnection.getOutputStream();
                outputStream.write(outputStr.getBytes("utf-8"));
                outputStream.close();
            }

            InputStream inputStream = httpURLConnection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while((str = bufferedReader.readLine())!= null){
                buffer.append(str);
            }

            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return buffer.toString();
    }

此方法通过指定URL,请求的方式和参数进行请求,使用流的方式发送参数和读取响应结果。该方法简单,没有设置http的请求属性等,示例代码在微信开发中可以实现功能。
在此方法中 参数outputStr是向微信服务器发送的json格式的数据或者xml结构的数据,友好性不太好,通常应该传递Map<String,Object> params 保存参数

Get请求

private static final String CHAR_SET = "UTF-8";
 public static String sendGet(String url, Map<String,Object> params){
        StringBuilder responseStr = null;
        StringBuilder paramsStr = new StringBuilder();
        if(params != null || params.size() > 0){
            for(Map.Entry<String,Object> entry : params.entrySet()){
                paramsStr.append(entry.getKey());
                paramsStr.append("=");
                try {
                    paramsStr.append(URLEncoder.encode(String.valueOf(entry.getValue()),CHAR_SET));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                paramsStr.append("&");
            }
        }
        URL URLstr = null;
        BufferedReader bufr = null;
        HttpURLConnection httpURLConnection = null;
        try {
            if(paramsStr != null && paramsStr.length() > 0){
                url = url + "?" + paramsStr.substring(0,paramsStr.length() - 1);
            }
            URLstr = new URL(url);
            httpURLConnection = (HttpURLConnection) URLstr.openConnection();
            httpURLConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            httpURLConnection.connect();
            responseStr = new StringBuilder();
            bufr = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),CHAR_SET));
            String str = null;
            while((str = bufr.readLine()) != null){
                responseStr.append(str);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            httpURLConnection.disconnect();
            if (bufr != null){
                try {
                    bufr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return  responseStr.toString();
    }

Post请求

public static String sendPost(String url, Map<String, Object> params){
        StringBuilder responseStr = null;
        StringBuilder paramsStr = new StringBuilder();
        if(params != null || params.size() > 0){
            for(Map.Entry<String,Object> entry : params.entrySet()){
                paramsStr.append(entry.getKey());
                paramsStr.append("=");
                try {
                    paramsStr.append(URLEncoder.encode(String.valueOf(entry.getValue()),CHAR_SET));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                paramsStr.append("&");
            }
        }
        URL URLstr = null;
        BufferedReader bufr = null;
        HttpURLConnection httpURLConnection = null;
        OutputStreamWriter osw = null;
        try {
            URLstr = new URL(url);
            httpURLConnection = (HttpURLConnection) URLstr.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setUseCaches(false);
            if(paramsStr != null && paramsStr.length() > 0){
                osw = new OutputStreamWriter(httpURLConnection.getOutputStream(),CHAR_SET);
                osw.write(paramsStr.substring(0,paramsStr.length() - 1));
                osw.flush();
            }
            bufr = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),CHAR_SET));
            String str = null;
            while((str = bufr.readLine()) != null){
                responseStr.append(str);
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(osw != null){
                try {
                    osw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
            if(bufr != null){
                try {
                    bufr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return responseStr.toString();
    }

通过对比sendGet和sendPost两种方法,发现不同之处有:

  • 在创建URL对象时,sendGet方法的url是直接拼接了参数,而sendPost方法没有,sendPost方法通过OutputStremWriter对象将参数直接写出
  • 在创建了HttpURLConnection对象后,sendGet方法调用了connect()方法,sendPost没有调用此方法,但是显示设置了RequestMethod为POST
  • 在设置参数sendGet方法显示设置了“Content-Type”,sendPost则省略了,该参数可以不显示设置,关于“application/x-www-form-urlencoded”详细解释,为什么可以不显示设置,详见:《HTTP中application/x-www-form-urlencoded字符说明》
  • 在sendPost方法中显示设置了DoOutput和DoInput为true,UseCaches为false

使用HttpClient

Get请求

public static String httpClienOfGet(String url,Map<String,Object> params){
        String res = "";
        StringBuilder paramsStr = null;
        if(params != null && params.size() > 0){
            for(Map.Entry<String,Object> entry : params.entrySet()){
                paramsStr.append(entry.getKey());
                paramsStr.append("=");
                try {
                    paramsStr.append(URLEncoder.encode(String.valueOf(entry.getValue()),CHAR_SET));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                paramsStr.append("&");
            }
        }

        if(paramsStr != null && paramsStr.length() > 0){
            url = url + "?" + paramsStr.substring(0,paramsStr.length() - 1);
        }
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        try {
            HttpResponse response = httpClient.execute(httpGet);
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                res = EntityUtils.toString(response.getEntity());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(httpClient != null){
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return res;
    }

Post请求

 public static String httpClientOfPost(String url, Map<String, Object> params){
        String res = "";
        List<NameValuePair> paramList = new ArrayList<NameValuePair>();
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost  httpPost = new HttpPost(url);

        if(params != null && params.size() > 0){
            for(Map.Entry<String,Object> entry : params.entrySet()){
                paramList.add(new BasicNameValuePair(entry.getKey(),String.valueOf(entry.getValue())));
            }
        }

        try {
            if(paramList.size() > 0){
                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(paramList,CHAR_SET);
                httpPost.setEntity(urlEncodedFormEntity);
            }
            HttpResponse response = httpClient.execute(httpPost);
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                res = EntityUtils.toString(response.getEntity());
            }
        } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(httpClient != null){
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return res;
    }

通过比较这两种方式,发现在创建请求方法时,对url处理不同,HttpGet的url直接拼接了参数,而HttpGet的url不做处理,参数则是通过了urlEncodedFormEntity 对象进行设置

通过Post请求发送接收json格式的数据

在微信开发时,通常要通过http发送json格式的数据,微信服务器返回的是json数据,包含了code和msg

public static String jsonOfPost(String url, String param){
        String res = "";
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Accept","application/json");
        httpPost.setHeader("Content-Type","application/json");
        String charSet = "UTF-8";
        HttpResponse response = null;

        try {
            StringEntity entity = new StringEntity(param,charSet);
            entity.setContentEncoding(charSet);
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            response = client.execute(httpPost);
            StatusLine statusLine = response.getStatusLine();
            int state = statusLine.getStatusCode();
            if(state == org.apache.http.HttpStatus.SC_OK){
                HttpEntity responseEntity = response.getEntity();
                res = EntityUtils.toString(responseEntity);
                return res;
            }else{
                System.out.println("请求出错");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }

关于http的请求总结到这里,有关于POST和GET请求的区别,详见:
https://blog.csdn.net/yaojianyou/article/details/1720913/
http://www.nowamagic.net/librarys/veda/detail/1919

参考的优秀博文:
https://www.cnblogs.com/mengrennwpu/p/6418114.html
https://blog.csdn.net/u010197591/article/details/51441399
https://blog.csdn.net/qq9808/article/details/78320816

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

微信开发(二)http请求工具类 的相关文章

  • CMake的add_library与target_link_libraries

    一 add library介绍 使用该命令可以在Linux下生成 xff08 静态 动态 xff09 库so或者 a文件 xff0c Windows下就是dll与lib文件 xff0c 它有两种命令格式 1 1 第一种格式 xff1a No
  • Linux下终止正在执行的shell脚本

    一 问题 Linux系统Shell中提交了一个脚本 xff0c 但是需要停止这个进程 xff0c 如何处理 xff1f 二 方案1 killall fileName 说明 xff1a killall是一个命令 xff0c 不是kill al
  • Qt对象树的销毁

    一 问题 在C 43 43 中中 xff0c 我们都知道 xff1a delete 和 new 必须配对使用 一 一对应 xff1a delete少了 xff0c 则内存泄露 为什么Qt使用new来创建一个控件 xff0c 但是却没有使用d
  • DNS域名解析之递归与非递归查询

    DNS域名解析之递归与非递归查询 递归查询迭代查询实例 递归查询 主机向本地域名服务器的查询一般是递归查询 xff1a 如果本地域名服务器不知道查询的IP地址 xff0c 那么本地域名服务器就会以DNS客户的身份向根域名服务器继续发生请求
  • spi,iic,uart,pcie区别

    一 spi SPI 是英语Serial Peripheral interface的缩写 xff0c 顾名思义就是串行外围设备接口 xff0c 是同步传输协议 xff0c 特征是 xff1a 设备有主机 xff08 master xff09
  • 决策树的介绍

    一 介绍 决策树 decision tree 是一类常见的机器学习方法 它是一种树形结构 xff0c 其中每个内部节点表示一个属性上的判断 xff0c 每个分支代表一个判断结果的输出 xff0c 最后每个叶节点代表一种分类结果 例如 xff
  • 支持向量机

    一 是否线性可分的问题 考虑图6 1中 xff0c A D共4个方框中的数据点分布 xff0c 一个问题就是 xff0c 能否画出一条直线 xff0c 将圆形点和方形点分开呢 xff1f 比如图6 2中 xff0c 方框A中的两组数据 xf
  • cmake 链接库名称扩展

    多个文件 macro span class token punctuation span configure lib by types OUTLIBS DebugSuffix span class token punctuation spa
  • 如何自定义TCP通信协议

    物联网行业智能硬件之间的通信 异构系统之间的对接 中间件的研发 以及各种即时聊天软件等 xff0c 都会涉及自定义协议 为了满足不同的业务场景的需要 xff0c 应用层之间通信需要实现各种各样的网络协议 以异构系统的对接为例 在早期 xff
  • 使用米联客FPGA开发板 固化程序失败

    问题描述 xff1a 使用米联客FPGA ZYNQ7020开发板 xff0c 在利用工程和FSBL生成BOOT bin和fsbl elf文件 烧录FLASH时 xff0c 总是失败 这个问题折腾我小半天 xff0c xff0c 无语了 后来
  • Qt串口接收数据长度不稳定问题

    最近在做一个实时接收数据的项目 xff0c 需要每2ms接收下位机发来的两帧数据 xff0c 算是串口高速接收 在使用的过程中 xff0c 发现串口接收的数据长度不稳定 xff0c 有时长有时短 代码如下 xff1a connect ser
  • git的使用入门

    1 添加个人信息 git config global user name 名字 git config global user email 邮箱 git config global user phone 手机号 查看是否提交 git conf
  • Python-OpenCV之形态学转换

    目标 学习不同的形态学操作 xff0c 例如腐蚀 xff0c 膨胀 xff0c 开运算 xff0c 闭运算等 我们要学习的函数有 xff1a cv2 erode xff0c cv2 dilate xff0c cv2 morphologyEx
  • 在windows10系统中搭建mmdetection(2020.7.19)

    参考博客 https blog csdn net david lee13 article details 102940221 本人使用的版本 python 61 3 6cuda 61 10 0cudnn 61 7 5 1pytorch 61
  • C语言字节对齐详解

    C语言字节对齐12345 不同系统下的C语言类型长度 Data TypeILP32ILP64LP64LLP64char8888short16161616int32643232long32646432long long64646464poin
  • 深入学习卷积神经网络中卷积层和池化层的意义

    xff08 文章转载自 xff1a https www cnblogs com wj 1314 p 9593364 html xff09 为什么要使用卷积呢 xff1f 在传统的神经网络中 xff0c 比如多层感知机 xff08 MLP x
  • 关于LSTM的units参数

    LSTM units input shape 3 1 这里的units指的是cell的个数么 xff1f 如果是 xff0c 按照LSTM原理这些cell之间应该是无连接的 xff0c 那units的多少其意义是什么呢 xff0c 是不是相
  • C语言的queue函数

    转自 xff1a https blog csdn net zhang2622765758 article details 81709820 queue 模板类的定义在 lt queue gt 头文件中 与stack 模板类很相似 xff0c
  • pip/anaconda修改镜像源,加快python模块安装速度

    文章来源 xff1a https blog csdn net leviopku article details 80113021 修改镜像源的原因是pip和conda默认国外镜像源 xff0c 所以每次安装模块pip install 或者
  • Python-PackagesNotFoundError: The following packages are not available from current channels

    Python PackagesNotFoundError The following packages are not available from current channels 转载自 xff1a https blog csdn ne

随机推荐

  • Linux 下静态链接库.a 和动态链接库.so 的生成

    1 库 所谓的库就是一种可执行代码的二进制形式 xff0c 可以被操作系统载入内存执行 2 静态库和动态库 静态库 a 文件的命名方式 xff1a libxxx a 库名前加 lib xff0c 后缀是 a 库名是 xxx 链接时间 xff
  • CSDN如何转载别人的博客

    在参考 如何快速转载CSDN中的博客 后 xff0c 由于自己不懂html以及markdown相关知识 xff0c 所以花了一些时间来弄明白怎么转载博客 xff0c 以下为转载CSDN博客步骤和一些知识小笔记 参考博客原址 xff1a ht
  • 你有一条linux命令学习之解压缩.tar .gz .xz .bz .zip

    下载的包解压还是压缩本地的包 xff0c 都要用到解压缩命令 1 tar tar命令生成的压缩包 1 命令语法 tar xcfvzjJ pathname tar file 2 参数 c 创建包 x 解压包 v 显示解压缩过程 f 指定包名
  • raspberry pi 3 ModelB 更换内核、文件系统初探

    1 镜像烧录 1 下载官方最新镜像 xff1a https www raspberrypi org downloads 2 Win32DiskImager烧录 xff1a https sourceforge net projects win
  • char类型与int类型的相互转换、

    相关知识 xff1a 1 计算机中的一个unsigned char型数据表示0 255 xff0c 而一个signed char型数据表示 128 43 127 xff0c 都是256的数字 这256个数字 xff0c 在计算机的存储单元都
  • 使用printf输出各种格式的字符串

    xfeff xfeff 分类 xff1a 43 43 主题 使用printf输出各种格式的字符串 日期 2004 06 29 43 43 1 原样输出字符串 printf 34 s 34 str 2 输出指定长度的
  • float型变量和“零值”比较的方法

    前一段时间读了一下林锐博士的 高质量C C 43 43 编程指南 xff0c 其中有一个比较经典的问题 请写出float x与 零值 比较的if语句 xff1f 当时只知道不能直接用float类型的值与0进行 61 61 或 61 比较 x
  • 全局变量和局部变量

    全局变量也称为外部变量 xff0c 它是在函数外部定义的变量 它不属于哪一个函数 xff0c 它属于一个源程序文件 其作用域是整个源程序 在函数中使用全局变量 xff0c 一般应作全局变量说明 只有在函数内经过说明的全局变量才能使用 但是在
  • c 内存管理

    其他相关链接 xff1a https blog csdn net wind19 article details 5964090 一 几个基本概念 在C语言中 xff0c 关于内存管理的知识点比较多 xff0c 如函数 变量 作用域 指针等
  • Springboot操作MongoDB,包括增改查及复杂操作

    单条件查询 使用BasicDBObject配置查询条件 List span class token generics function span class token punctuation lt span AbstractMongoEn
  • 搭建Spark实战环境(3台linux虚拟机集群)(一)样板机的搭建

    系统及软件配置 系统配置 内存 xff1a 16g 2400 cpu xff1a i5 9400F 软件配置 Windows 10 1903版本VMware workstation 15 10CentOS centos release 7
  • 独立个人项目开发心得 - 任务切分、挑战性、实用性和半途而废

    在写文章前容许我啰嗦一下 xff1a 对于软件开发 xff0c 我走了不少弯路 xff0c 有时觉得自己作为API侠 xff0c 无所不能 xff0c 有时又觉得自己很多LeetCode题写不出来 xff0c 无能为力 我有一个博客 xff
  • 传统软件服务器与游戏服务器架构区别

    项目智能客服爬虫SLG游戏语言javapythonkotlin模型异步事件驱动可能没什么模型可言actor模型传输协议httphttptcp 43 netty传输结构jsonjsonprotobuf数据库oracle xff0c redis
  • Linux C++ Socket实战

    本文主要介绍Linux C 43 43 基础Socket网络编程 大部分知识来自于网站 xff1a https www geeksforgeeks org socket programming cc Socket编程状态图 从图中可以看到
  • CSAPP第二章-信息的表示与处理-随手记

    仅作为学习 深入理解计算机系统 第二章时的笔记 xff0c 仅记录对自己有启发的部分 xff0c 不作为知识整理 xff08 直接看电子书就可以了 xff09 因为这本书知识点非常多 xff0c 所以我会抽时间多次阅读 xff0c 本文也会
  • Vue的路由配置及手动改地址栏为啥又跳转回来??

    vue cli xff08 vue脚手架 xff09 超详细教程 xff1a https blog csdn net wulala hei article details 85000530 这个教程里面是使用 vue init webpac
  • GPS卫星轨道

    GPS卫星轨道周期几乎是24小时 xff0c 而自己的卫星在太阳同步轨道上的周期大概是1 5个小时 xff0c 那么就是说太阳同步轨道已经绕几周了 xff0c GPS卫星才饶一周 所以当算多普勒频移的时候只需要算出GPS一个周期时间内的多普
  • 快速了解S7-1200 PLC的存储器及存储区的寻址方式

    S7 1200 PLC的存储器地址包括输入I 输出Q 位存储器M 数据块DB xff0c 以及本地或临时存储器L eg xff1a 标识存储区M0 0 MB0 MW0 MD0 分别是 B位 字节B 8位 字W 16位 双字D 32位 输入过
  • 网络编程之UDP简单示例

    UDP编程函数recvfrom inet pton sendto UDP协议 user data protrol 用户数据协议特点 xff1a TCP xff1a 面向连接 gt 一定双方连接上了才能进行通信 xff01 UDP xff1a
  • 微信开发(二)http请求工具类

    说明 进行微信开发 xff0c 后台程序需要与微信服务器进行交互 xff0c 通过调用接口来完成服务 xff0c 阅读微信开发文档 xff0c 发现接口的调用都是通过http请求进行的 xff0c 所以必须有个HttpUtil来支撑 xff