前言:

  在做小程序的开发时需要获取用户的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. Linux添加防火墙、iptables的安装和配置

    由于centos7默认是使用firewall作为防火墙,下面介绍如何将系统的防火墙设置为iptables. #停止firewall systemctl stop firewall.service #禁 ...

  2. Linux初探之如何查看帮助文档自学命令

    linux命令种类繁多,参数各异,要每个都记住除非是过目不忘的神人,否则你只能记住常用的那几个,等到 要用时还是得靠--help,man,info这些命令去读文档,可是这些文档看起来也不那么直观,所以 ...

  3. 服务端负载监控-参考srs服务器源码

    #include <map> #include <stdio.h> using namespace std; struct SrsMemoryObject { void* pt ...

  4. Linux 安装配置 NET模式网络环境配置

    1.下载linux:发行版 Ubuntu  REdHat centos Debain Fedora,SUSE,OpenSUSEcentos 6.xcentos 7.x在虚拟机(VmWare)上 安装l ...

  5. 关于int和Integer缓存(一):以及设计构想(享元模式)

    关于Integer的值缓存:在介绍Integer的值缓存之前,我们需要了解的是,java中的包装类型,我们都知道java中有包装类型int                     Integer    ...

  6. js函数和封装

    $就是jquery对象,$()就是jQuery(),在里面可以传参数,作用就是获取元素 js对象与jQuery对象的区别:jQuery对象是一个数组,jQuery对象转为js对象:[0] 取第一个即可 ...

  7. docker-compose权限不够

    root@kali:~# docker-compose version -bash: /usr/local/bin/docker-compose: 权限不够 chmod +x /usr/local/b ...

  8. lsyncd替代inotify+rsync实现实时同步

    因公司业务需要需要实时同步日志文件,刚一开始使用的是inotify+rsync来实现实时同步,但时间久而久之发现同步的速度越来越慢,往往延迟好几个小时.查了一下网上的inotify+rsync方案基本 ...

  9. blender Text on Curve Text on Sphere

    Text on Curve Shift + A 添加一个 BezierCurve Shift + A 添加一个 Text,Tab 编辑,再次 Tab 退回 Object Mode 选中 Text,Ad ...

  10. python glob.glob()

    glob()函数可以将某目录下所有跟通配符模式相同的文件放到一个列表中,有了这个函数,我们再想生成所有文件的列表就不需要使用for循环遍历目录了,直接使用glob.glob(path+pattern) ...