前言:

  在做小程序的开发时需要获取用户的openId用来做唯一标识,来获取对应用户的相关数据

  官方的文档说明上有四个必须传的参数

  其中appId和appSecret可在自己的微信公众号平台上获取,同时这些也是属于私密信息,应该妥善保管的,因为微信手机客户端是很容易反编译获取到这些信息的,所以在前端的ajax请求将这些参数传到后台是不可取的,最好的方式是将这两个参数在后台传入,然后发送请求至官方接口

1.Http请求工具类

  

package com.btw.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Map; public class HttpUtil {
/**
* 请求类型: GET
*/
public final static String GET = "GET";
/**
* 请求类型: POST
*/
public final static String POST = "POST"; /**
* 模拟Http Get请求
* @param urlStr
* 请求路径
* @param paramMap
* 请求参数
* @return
* @throws Exception
*/
public static String get(String urlStr, Map<String, String> paramMap) throws Exception{
urlStr = urlStr + "?" + getParamString(paramMap);
HttpURLConnection conn = null;
try{
//创建URL对象
URL url = new URL(urlStr);
//获取URL连接
conn = (HttpURLConnection) url.openConnection();
//设置通用的请求属性
setHttpUrlConnection(conn, GET);
//建立实际的连接
conn.connect();
//获取响应的内容
return readResponseContent(conn.getInputStream());
}finally{
if(null!=conn) conn.disconnect();
}
} /**
* 模拟Http Post请求
* @param urlStr
* 请求路径
* @param paramMap
* 请求参数
* @return
* @throws Exception
*/
public static String post(String urlStr, Map<String, String> paramMap) throws Exception{
HttpURLConnection conn = null;
PrintWriter writer = null;
try{
//创建URL对象
URL url = new URL(urlStr);
//获取请求参数
String param = getParamString(paramMap);
//获取URL连接
conn = (HttpURLConnection) url.openConnection();
//设置通用请求属性
setHttpUrlConnection(conn, POST);
//建立实际的连接
conn.connect();
//将请求参数写入请求字符流中
writer = new PrintWriter(conn.getOutputStream());
writer.print(param);
writer.flush();
//读取响应的内容
return readResponseContent(conn.getInputStream());
}finally{
if(null!=conn) conn.disconnect();
if(null!=writer) writer.close();
}
} /**
* 读取响应字节流并将之转为字符串
* @param in
* 要读取的字节流
* @return
* @throws IOException
*/
private static String readResponseContent(InputStream in) throws IOException{
Reader reader = null;
StringBuilder content = new StringBuilder();
try{
reader = new InputStreamReader(in);
char[] buffer = new char[1024];
int head = 0;
while( (head=reader.read(buffer))>0 ){
content.append(new String(buffer, 0, head));
}
return content.toString();
}finally{
if(null!=in) in.close();
if(null!=reader) reader.close();
}
} /**
* 设置Http连接属性
* @param conn
* http连接
* @return
* @throws ProtocolException
* @throws Exception
*/
private static void setHttpUrlConnection(HttpURLConnection conn, String requestMethod) throws ProtocolException{
conn.setRequestMethod(requestMethod);
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("Accept-Language", "zh-CN");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
conn.setRequestProperty("Proxy-Connection", "Keep-Alive");
if(null!=requestMethod && POST.equals(requestMethod)){
conn.setDoOutput(true);
conn.setDoInput(true);
}
} /**
* 将参数转为路径字符串
* @param paramMap
* 参数
* @return
*/
private static String getParamString(Map<String, String> paramMap){
if(null==paramMap || paramMap.isEmpty()){
return "";
}
StringBuilder builder = new StringBuilder();
for(String key : paramMap.keySet() ){
builder.append("&")
.append(key).append("=").append(paramMap.get(key));
}
return builder.deleteCharAt(0).toString();
}
}

  

其中请求参数已经封装成map的形式,非常方便

2.请求接口

在这个接口我们只需要接收一个code的参数,然后用String类型接收Util类返回的数据即可,其中的url为官方接口地址

package com.btw.controller;

import com.btw.util.AppConstant;
import com.btw.util.HttpUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map; @RestController
@RequestMapping("/system")
public class SecretController {
@RequestMapping(value = "/getOpenId",method = RequestMethod.GET)
public String getOpenid(HttpServletRequest request,HttpServletResponse response, @RequestParam String code){
Map<String,String> paramMap=new HashMap<>();
paramMap.put("appid", AppConstant.AppId);
paramMap.put("secret",AppConstant.AppSecret);
paramMap.put("js_code",code);
paramMap.put("grant_type","authorization_code");
String url="https://api.weixin.qq.com/sns/jscode2session";
String res=null;
try {
res=HttpUtil.post(url,paramMap);
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
}

3.前端Ajax请求

服务器内部模拟Http请求的更多相关文章

  1. NodeJs本地搭建服务器,模拟接口请求,获取json数据

    最近在学习Node.js,虽然就感觉学了点皮毛,感觉这个语言还不错,并且也会一步步慢慢的学着的,这里实现下NodeJs本地搭建服务器,模拟接口请求,获取json数据. 具体的使用我就不写了,这个博客写 ...

  2. Node.js创建服务器和模拟客户端请求

    1. 何为服务器 服务器是某种长期运行,等待请求资源的应用程序 2. 常见Web应用架构 3. 如何创建web服务器 Web服务器是使用HTTP协议,等待客户端连接后请求资源的驻守应用程序:HTTP协 ...

  3. 关于wcf异常异常信息:由于内部错误,服务器无法处理该请求。有关该错误的详细信息,请打开服务器上的 IncludeExceptionDetailInFaults (从 ServiceBehaviorAttribut

    异常信息:由于内部错误,服务器无法处理该请求.有关该错误的详细信息,请打开服务器上的 IncludeExceptionDetailInFaults (从 ServiceBehaviorAttribut ...

  4. C#模拟httpwebrequest请求_向服务器模拟cookie发送

    使用C#代码模拟web请求,是一种常用的方法,以前没专门整理过,这里暂时贴上自己整理的完整代码,以后再做梳理: public class MyRequest { #region 辅助方法 public ...

  5. js_html_input中autocomplete="off"在chrom中失效的解决办法 使用JS模拟锚点跳转 js如何获取url参数 C#模拟httpwebrequest请求_向服务器模拟cookie发送 实习期学到的技术(一) LinqPad的变量比较功能 ASP.NET EF 使用LinqPad 快速学习Linq

    js_html_input中autocomplete="off"在chrom中失效的解决办法 分享网上的2种办法: 1-可以在不需要默认填写的input框中设置 autocompl ...

  6. PHP+SOCKET 模拟HTTP请求

    HTTP消息结构 客户端请求包括四部份:请求行(状态行).请求头.空行.请求主体(数据),如下图: 服务端响应包括四部份:响应行(状态行).响应头.空行.响应主体(数据),如图: HTTP请求方法: ...

  7. requests模拟浏览器请求模块初识

    requests模拟浏览器请求模块初识  一.下载 requests模拟浏览器请求模块属于第三方模块 源码下载地址http://docs.python-requests.org/zh_CN/lates ...

  8. ASP模拟POST请求异步提交数据的方法

    这篇文章主要介绍了ASP模拟POST请求异步提交数据的方法,本文使用MSXML2.SERVERXMLHTTP.3.0实现POST请求,需要的朋友可以参考下 有时需要获取远程网站的某些信息,而服务器又限 ...

  9. HttpClientUtil [使用apache httpclient模拟http请求]

    基于httpclient-4.5.2 模拟http请求 以get/post方式发送json请求,并获取服务器返回的json -------------------------------------- ...

随机推荐

  1. 【OpenLayers】入门教程地址

    [OpenLayers]入门教程地址:  点击进入   http://anzhihun.coding.me/ol3-primer/index.html 简书地址 :  http://www.jians ...

  2. JFrame显示刷新

    1 import java.awt.BorderLayout; 2 import java.awt.Font; 3 import java.awt.event.ActionEvent; 4 impor ...

  3. Win10安装gcc

    使用MinGW安装gcc 1.下载MinGW,地址 https://sourceforge.net/projects/mingw/files/ ,选择Download mingw-get-setup. ...

  4. Ubuntu 16.04 Install NVidia Driver (download from nvidia official site)

    sudo apt-get update sudo apt-mark hold libreoffice sudo apt-get update && sudo apt-get upgra ...

  5. AQS实现原理

    AQS实现原理 AQS中维护了一个volatile int state(共享资源)和一个CLH队列.当state=1时代表当前对象锁已经被占用,其他线程来加锁时则会失败,失败的线程被放入一个FIFO的 ...

  6. Tomcat集群Cluster实现原理

    1.Tomcat集群         Tomcat集群的问题之一是如何处理Session,Session是有状态的,请求到了Tomcat,后续流传是要根据上下文(Context)来进行的.我们可以改造 ...

  7. Springboot自带定时任务实现动态配置Cron参数

    同学们,我今天分享一下SpringBoot动态配置Cron参数.场景是这样子的:后台管理界面对定时任务进行管理,可动态修改执行时间,然后保存入库,每次任务执行前从库里查询时间,以达到动态修改Cron参 ...

  8. 基于源码编译的lnmp架构实现论坛的搭建及memcache的应用

    系统环境: RHEL6 x86-64 selinux and iptables disabled LNMP代表的就是:Linux系统下Nginx+MySQL+PHP这种网站服务器架构 Linux是一类 ...

  9. Django使用富文本编辑器ckediter

    1 - 安装 pip install django-ckeditor 2 - 注册APP ckeditor 3 - 由于djang-ckeditor在ckeditor-init.js文件中使用了JQu ...

  10. 稚晖君-最小linux服务器运行 nginx + netcore

    华为天才少年, B站科技大神,稚晖君(自称野生钢铁侠),多少科技爱好者拜服在他的全方位技术栈 今天我们就去入手一个他的量产产品 号称最小linux电脑 的"夸克" 到手之后,我们马 ...