微信小程序獲取登錄ID

這個東西還是比較簡單的,我是記錄一下,下次做的話 就不在翻微信官網了(PS :雖然我覺得可能那時候就更新換代了 )

 @Value("${wx.appletUrl}")
      private  String appletUrl ;
//      private final static String appletUrl = "https://api.weixin.qq.com/sns/jscode2session";
      @Value("${wx.appId}")
      private String APPID;
      @Value("${wx.secret}")
      private String SECRET;

APPID和 SECRET 應該就不用多說了

    String requestURL = appletUrl +"?appid="+wxAPPID+"&secret="+wxSECRET+"&js_code="+jsCode+"&grant_type=authorization_code";
//        String re = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
        String json = HttpClientUtil.doGet(requestURL);
        Map<String,String> resultMap = JacksonUtil.toObject(json, Map.class);
        
        if(resultMap.containsKey("session_key")) {
            System.out.println(resultMap.get("session_key"));
            System.out.println(resultMap.get("openid"));
            result.setSessionKey(resultMap.get("session_key"));
            result.setOpenid(resultMap.get("openid"));
            
        }else {
            System.out.println(resultMap.get("errcode"));
            log.error("error getWXAppletsID errcode   ======="+ resultMap.get("errcode") + "errmsg       ======="+resultMap.get("errmsg")+appletUrl  );
            result.failure(resultMap.get("errcode"));
        }

東西也就是如此至少 然後就是根據自己公司的邏輯來處理業務
另 將HttpClientUtil 附在下面

package com.kting.micro.service.base.commons.util;

import java.nio.charset.CodingErrorAction;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.config.MessageConstraints;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.kting.micro.service.vo.album.ChannelVO;

public class HttpClientUtil {
	private static final String encoding = "UTF-8";
	private final static int connectTimeout = 5000;

	private static PoolingHttpClientConnectionManager connManager = null;
	private static CloseableHttpClient httpclient = null;

	static {
		try {
			Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create().register("http",
					PlainConnectionSocketFactory.getSocketFactory()).register("https", SSLConnectionSocketFactory.getSocketFactory()).build();
			connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
			httpclient = HttpClients.custom().setConnectionManager(connManager).build();
			// Create socket configuration
			SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
			connManager.setDefaultSocketConfig(socketConfig);
			// Create message constraints
			MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(200).setMaxLineLength(2000).build();
			// Create connection configuration
			ConnectionConfig connectionConfig = ConnectionConfig.custom().setMalformedInputAction(CodingErrorAction.IGNORE).setUnmappableInputAction(
					CodingErrorAction.IGNORE).setCharset(Consts.UTF_8).setMessageConstraints(messageConstraints).build();
			connManager.setDefaultConnectionConfig(connectionConfig);
			connManager.setMaxTotal(200);
			connManager.setDefaultMaxPerRoute(20);
		} catch (Exception e) {

		}
	}
	public static String doPost(String url_str, String param) {
		return doPost(url_str,param,"");
	}

	public static String doPost(String url_str, String param,String token) {
		HttpPost post = new HttpPost(url_str);
		try {
			post.setHeader("User-Agent", "agx.ims");
			post.setHeader("Content-type", "application/json");
			post.setHeader("X-Auth-Token", token);
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(connectTimeout).setConnectTimeout(connectTimeout)
					.setConnectionRequestTimeout(connectTimeout).setExpectContinueEnabled(false).build();
			post.setConfig(requestConfig);
			post.setEntity(new StringEntity(param, encoding));
			
			CloseableHttpResponse response = httpclient.execute(post);

			try {
				System.out.println(response.getStatusLine().getStatusCode());
				if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
					HttpEntity entity = response.getEntity();
					try {
						if (entity != null) {
							return EntityUtils.toString(entity, encoding);
						}
					} finally {
						if (entity != null) {
							entity.getContent().close();
						}
					}
				}
			} finally {
				if (response != null) {
					response.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			post.releaseConnection();
		}
		return null;
	}
	public static String doGet(String url_str) {
		return doGet(url_str,"");
	}
	public static String doGet(String url_str,String token) {
		HttpGet get = new HttpGet(url_str);
		try {
			get.setHeader("User-Agent", "agx.ims");
			get.setHeader("Content-type", "application/json");
			get.setHeader("X-Auth-Token", token);
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(connectTimeout).setConnectTimeout(connectTimeout)
					.setConnectionRequestTimeout(connectTimeout).setExpectContinueEnabled(false).build();
			get.setConfig(requestConfig);

			CloseableHttpResponse response = httpclient.execute(get);
			try {
				HttpEntity entity = response.getEntity();
				try {
					if (entity != null) {
						return EntityUtils.toString(entity, encoding);
					}
				} finally {
					if (entity != null) {
						entity.getContent().close();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (response != null) {
					response.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			get.releaseConnection();
		}
		return null;
	}

	/**
	 * HTTPS請求,默認超時爲5S
	 * 
	 * @param reqURL
	 * @param params
	 * @return
	 */
	public static String connectPostHttps(String reqURL, Map<String, String> params) {

		String responseContent = null;

		HttpPost httpPost = new HttpPost(reqURL);
		try {
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(connectTimeout).setConnectTimeout(connectTimeout)
					.setConnectionRequestTimeout(connectTimeout).build();

			List<NameValuePair> formParams = new ArrayList<NameValuePair>();
			httpPost.setEntity(new UrlEncodedFormEntity(formParams, Consts.UTF_8));
			httpPost.setConfig(requestConfig);
			httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
			// 綁定到請求 Entry
			for (Map.Entry<String, String> entry : params.entrySet()) {
				formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}
			CloseableHttpResponse response = httpclient.execute(httpPost);
			try {
				// 執行POST請求
				HttpEntity entity = response.getEntity(); // 獲取響應實體
				try {
					if (null != entity) {
						responseContent = EntityUtils.toString(entity, Consts.UTF_8);
					}
				} finally {
					if (entity != null) {
						entity.getContent().close();
					}
				}
			} finally {
				if (response != null) {
					response.close();
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			httpPost.releaseConnection();
		}
		return responseContent;

	}

	public static String doPost2(String hwAuthUrl, Map<String, Object> param) {
		// TODO Auto-generated method stub

		return null;
	}
	public static void main(String[] args) {
	    String url_str = "http://hmf-api-dev.kting.cn:90/api/v1/platform/channel";
	    HttpGet get = new HttpGet(url_str);
        try {
            get.setHeader("Code", "DT45MSWQIAQ761J");
            get.setHeader("Content-type", "application/json");
            get.setHeader("Authorization", "Authorization:Digest nonce=cb503f80762a4206949c7d57830d2750,created=2017-07-01T09:00:00Z,response=security:BD03032BFCB840FAE08F98AD07F765401834D73F2636278B047D1C5988B4D86C");
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(connectTimeout).setConnectTimeout(connectTimeout)
                    .setConnectionRequestTimeout(connectTimeout).setExpectContinueEnabled(false).build();
            get.setConfig(requestConfig);

            CloseableHttpResponse response = httpclient.execute(get);
            try {
                HttpEntity entity = response.getEntity();
                try {
                    if (entity != null) {
                         String string = EntityUtils.toString(entity, encoding);
                         System.out.println(string);
                         List<ChannelVO> object = JacksonUtil.toObject(string, List.class);
                         for (ChannelVO channelVO : object) {
                            
                         }
                    }
                } finally {
                    if (entity != null) {
                        entity.getContent().close();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (response != null) {
                    response.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            get.releaseConnection();
        }
	    
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章