java 获取微信 页面授权 获取用户openid

Posted 刘威jcw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 获取微信 页面授权 获取用户openid相关的知识,希望对你有一定的参考价值。

先调用微信的地址 跳转https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx4b4009c4fce00e0c&redirect_uri=这里填写你要跳到请求页面授权域名l&response_type=code&scope=snsapi_base&state=123#wechat_redirect

返回redirect_uri/?code=""&status="";

拿到code就可获取openid以及用户信息

 

先上 工具类

  1 package com.yulv.utils;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.IOException;
  5 import java.io.InputStream;
  6 import java.io.InputStreamReader;
  7 import java.io.OutputStream;
  8 import java.io.OutputStreamWriter;
  9 import java.net.HttpURLConnection;
 10 import java.net.InetSocketAddress;
 11 import java.net.Proxy;
 12 import java.net.URL;
 13 import java.net.URLConnection;
 14 import java.util.Iterator;
 15 import java.util.Map;
 16 
 17 
 18 public class HttpRequestor {
 19      private String charset = "utf-8";
 20         private Integer connectTimeout = null;
 21         private Integer socketTimeout = null;
 22         private String proxyHost = null;
 23         private Integer proxyPort = null;
 24         
 25         /**
 26          * Do GET request
 27          * @param url
 28          * @return
 29          * @throws Exception
 30          * @throws IOException
 31          */
 32         public String doGet(String url) throws Exception {
 33             
 34             URL localURL = new URL(url);
 35             
 36             URLConnection connection = openConnection(localURL);
 37             HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
 38             
 39             httpURLConnection.setRequestProperty("Accept-Charset", charset);
 40             httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
 41             
 42             InputStream inputStream = null;
 43             InputStreamReader inputStreamReader = null;
 44             BufferedReader reader = null;
 45             StringBuffer resultBuffer = new StringBuffer();
 46             String tempLine = null;
 47             
 48             if (httpURLConnection.getResponseCode() >= 300) {
 49                 throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
 50             }
 51             
 52             try {
 53                 inputStream = httpURLConnection.getInputStream();
 54                 inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
 55                 reader = new BufferedReader(inputStreamReader);
 56                 
 57                 while ((tempLine = reader.readLine()) != null) {
 58                     resultBuffer.append(tempLine);
 59                 }
 60                 
 61             } finally {
 62                 
 63                 if (reader != null) {
 64                     reader.close();
 65                 }
 66                 
 67                 if (inputStreamReader != null) {
 68                     inputStreamReader.close();
 69                 }
 70                 
 71                 if (inputStream != null) {
 72                     inputStream.close();
 73                 }
 74                 
 75             }
 76 
 77             return resultBuffer.toString();
 78         }
 79         
 80         /**
 81          * Do POST request
 82          * @param url
 83          * @param parameterMap
 84          * @return
 85          * @throws Exception 
 86          */
 87         public String doPost(String url, Map parameterMap) throws Exception {
 88             
 89             /* Translate parameter map to parameter date string */
 90             StringBuffer parameterBuffer = new StringBuffer();
 91             if (parameterMap != null) {
 92                 Iterator iterator = parameterMap.keySet().iterator();
 93                 String key = null;
 94                 String value = null;
 95                 while (iterator.hasNext()) {
 96                     key = (String)iterator.next();
 97                     if (parameterMap.get(key) != null) {
 98                         value = (String)parameterMap.get(key);
 99                     } else {
100                         value = "";
101                     }
102                     
103                     parameterBuffer.append(key).append("=").append(value);
104                     if (iterator.hasNext()) {
105                         parameterBuffer.append("&");
106                     }
107                 }
108             }
109             
110             System.out.println("POST parameter : " + parameterBuffer.toString());
111             
112             URL localURL = new URL(url);
113             
114             URLConnection connection = openConnection(localURL);
115             HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
116             
117             httpURLConnection.setDoOutput(true);
118             httpURLConnection.setRequestMethod("POST");
119             httpURLConnection.setRequestProperty("Accept-Charset", charset);
120             httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
121             httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterBuffer.length()));
122             
123             OutputStream outputStream = null;
124             OutputStreamWriter outputStreamWriter = null;
125             InputStream inputStream = null;
126             InputStreamReader inputStreamReader = null;
127             BufferedReader reader = null;
128             StringBuffer resultBuffer = new StringBuffer();
129             String tempLine = null;
130             
131             try {
132                 outputStream = httpURLConnection.getOutputStream();
133                 outputStreamWriter = new OutputStreamWriter(outputStream);
134                 
135                 outputStreamWriter.write(parameterBuffer.toString());
136                 outputStreamWriter.flush();
137                 
138                 if (httpURLConnection.getResponseCode() >= 300) {
139                     throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
140                 }
141                 
142                 inputStream = httpURLConnection.getInputStream();
143                 inputStreamReader = new InputStreamReader(inputStream);
144                 reader = new BufferedReader(inputStreamReader);
145                 
146                 while ((tempLine = reader.readLine()) != null) {
147                     resultBuffer.append(tempLine);
148                 }
149                 
150             } finally {
151                 
152                 if (outputStreamWriter != null) {
153                     outputStreamWriter.close();
154                 }
155                 
156                 if (outputStream != null) {
157                     outputStream.close();
158                 }
159                 
160                 if (reader != null) {
161                     reader.close();
162                 }
163                 
164                 if (inputStreamReader != null) {
165                     inputStreamReader.close();
166                 }
167                 
168                 if (inputStream != null) {
169                     inputStream.close();
170                 }
171                 
172             }
173 
174             return resultBuffer.toString();
175         }
176 
177         private URLConnection openConnection(URL localURL) throws IOException {
178             URLConnection connection;
179             if (proxyHost != null && proxyPort != null) {
180                 Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
181                 connection = localURL.openConnection(proxy);
182             } else {
183                 connection = localURL.openConnection();
184             }
185             return connection;
186         }
187         
188         /**
189          * Render request according setting
190          * @param request
191          */
192         private void renderRequest(URLConnection connection) {
193             
194             if (connectTimeout != null) {
195                 connection.setConnectTimeout(connectTimeout);
196             }
197             
198             if (socketTimeout != null) {
199                 connection.setReadTimeout(socketTimeout);
200             }
201             
202         }
203 
204         /*
205          * Getter & Setter
206          */
207         public Integer getConnectTimeout() {
208             return connectTimeout;
209         }
210 
211         public void setConnectTimeout(Integer connectTimeout) {
212             this.connectTimeout = connectTimeout;
213         }
214 
215         public Integer getSocketTimeout() {
216             return socketTimeout;
217         }
218 
219         public void setSocketTimeout(Integer socketTimeout) {
220             this.socketTimeout = socketTimeout;
221         }
222 
223         public String getProxyHost() {
224             return proxyHost;
225         }
226 
227         public void setProxyHost(String proxyHost) {
228             this.proxyHost = proxyHost;
229         }
230 
231         public Integer getProxyPort() {
232             return proxyPort;
233         }
234 
235         public void setProxyPort(Integer proxyPort) {
236             this.proxyPort = proxyPort;
237         }
238 
239         public String getCharset() {
240             return charset;
241         }
242 
243         public void setCharset(String charset) {
244             this.charset = charset;
245         }
246 }

 

 

 

直接获取

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        String code = request.getParameter("code");
        String appid = "wx4b4009c4fce00e0c";
        String secret = "4d3aea976157935e563f8ef01c7a4293";
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+wxCode+"&grant_type=authorization_code";
        //第一次请求 获取access_token 和 openid
        String  oppid = new HttpRequestor().doGet(requestUrl);
        JSONObject oppidObj =JSONObject.fromObject(oppid);
        String access_token = (String) oppidObj.get("access_token");
        String openid = (String) oppidObj.get("openid");
        String requestUrl2 = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
        String userInfoStr = new HttpRequestor().doGet(requestUrl2);
        JSONObject wxUserInfo =JSONObject.fromObject(userInfoStr); 
}

 

以上是关于java 获取微信 页面授权 获取用户openid的主要内容,如果未能解决你的问题,请参考以下文章

微信公众平台关于fakeid和openid的 区别

h5页面获取微信授权登录

Java实现微信登录

如何获取微信网页授权

微信网页授权获取用户基本信息

如何获取微信用户的Openid详解