前言:

  在做小程序的开发时需要获取用户的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. C# 异步锁 await async锁,lock,Monitor,SemaphoreSlim

    异步方法内无法使用Monitor 和lock 所以只能用System.Threading.SemaphoreSlim了 //Semaphore (int initialCount, int maxim ...

  2. 【java web】过滤器filter

    一.过滤器简介 过滤器filter依赖于servlet容器 所谓过滤器顾名思义是用来过滤的,Java的过滤器能够为我们提供系统级别的过滤,也就是说,能过滤所有的web请求, 这一点,是拦截器无法做到的 ...

  3. 【IDE】WebStorm常用快捷键

    WebStorm常用快捷键 1. ctrl + shift + n: 打开工程中的文件,目的是打开当前工程下任意目录的文件. 2. ctrl + j: 输出模板 3. ctrl + b: 跳到变量申明 ...

  4. JDBC中的元数据——1.数据库元数据

    package metadata; import java.sql.Connection; import java.sql.DatabaseMetaData; import javax.sql.Dat ...

  5. Servlet常见问题

    时间:2016-12-6 23:18 java.lang.ClassNotFoundException: org.apache.commons.collections.FastHashMapcommo ...

  6. Go测试--性能测试分析

    目录 前言 认识数据 benchstat 分析一组样本 分析两组样本 小结 前言 benchmark测试是实际项目中经常使用的性能测试方法,我们可以针对某个函数或者某个功能点增加benchmark测试 ...

  7. Java基础和常用框架的面试题

    前言 最近学校也催着找工作了,于是刷了一些面试题,学习了几篇大佬优秀的博客,总结了一些自认为重要的知识点:听不少职场前辈说,对于应届毕业生,面试时只要能说到核心重要的点,围绕这个点说一些自己的看法,面 ...

  8. 已知三角形ABC为锐角三角形,求 sinA + sinB·sin(C/2) 的最大值。

    已知三角形ABC为锐角三角形,求 sinA + sinBsin(C/2) 的最大值. 解:Δ := sinA + sinB·sin(C/2) = sin(B+C) + sinB·sin(C/2) = ...

  9. SpringBoot笔记(4)

    一.请求处理 1.1 常用参数注解使用 注解 使用 @PathVariable 获取URI模板指定请求,并赋值到变量中,不指定可以将所有请求放到map中,但是健值都为String @RequestHe ...

  10. 记一次 .NET 某新能源汽车锂电池检测程序 UI挂死分析

    更多高质量干货:参见我的 GitHub: dotnetfly 一:背景 1. 讲故事 这世间事说来也奇怪,近两个月有三位朋友找到我,让我帮忙分析下他的程序hangon现象,这三个dump分别涉及: 医 ...