HttpClient(4.5) 使用实例(微信API,网页授权Oauth2.0)

来源:互联网 发布:淘宝小李子假货 编辑:程序博客网 时间:2024/05/24 04:42

设置头信息:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. CloseableHttpClient httpClient = HttpClientBuilder.create().  
  2.                 setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()).  
  3.                 setRedirectStrategy(new DefaultRedirectStrategy()).setDefaultHeaders(new ArrayList<Header>()).  
  4.                 setDefaultCookieStore(cookieStore).  
  5.                 setDefaultRequestConfig(requestConfig).build();  
  6.   
  7.         HttpGet httpGet = new HttpGet(url);  
  8.         httpGet.setHeader("Content-Type""application/x-www-form-urlencoded");  

HttpClientUtil:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. import org.apache.http.Consts;  
  2. import org.apache.http.HttpEntity;  
  3. import org.apache.http.NameValuePair;  
  4. import org.apache.http.ParseException;  
  5. import org.apache.http.client.CookieStore;  
  6. import org.apache.http.client.config.AuthSchemes;  
  7. import org.apache.http.client.config.CookieSpecs;  
  8. import org.apache.http.client.config.RequestConfig;  
  9. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  10. import org.apache.http.client.methods.CloseableHttpResponse;  
  11. import org.apache.http.client.methods.HttpGet;  
  12. import org.apache.http.client.methods.HttpPost;  
  13. import org.apache.http.client.protocol.HttpClientContext;  
  14. import org.apache.http.config.Registry;  
  15. import org.apache.http.config.RegistryBuilder;  
  16. import org.apache.http.conn.socket.ConnectionSocketFactory;  
  17. import org.apache.http.conn.socket.PlainConnectionSocketFactory;  
  18. import org.apache.http.conn.ssl.NoopHostnameVerifier;  
  19. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;  
  20. import org.apache.http.cookie.Cookie;  
  21. import org.apache.http.impl.client.*;  
  22. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;  
  23. import org.apache.http.util.EntityUtils;  
  24.   
  25. import javax.net.ssl.SSLContext;  
  26. import javax.net.ssl.TrustManager;  
  27. import javax.net.ssl.X509TrustManager;  
  28. import java.io.IOException;  
  29. import java.security.KeyManagementException;  
  30. import java.security.NoSuchAlgorithmException;  
  31. import java.security.cert.CertificateException;  
  32. import java.security.cert.X509Certificate;  
  33. import java.util.Arrays;  
  34. import java.util.List;  
  35.   
  36. /** 
  37.  * Created by Administrator on 2015/11/28. 
  38.  */  
  39. public class HttpClientUtil {  
  40.     private static HttpClientContext context = HttpClientContext.create();  
  41.     private static RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(120000).setSocketTimeout(60000)  
  42.             .setConnectionRequestTimeout(60000).setCookieSpec(CookieSpecs.STANDARD_STRICT).  
  43.                     setExpectContinueEnabled(true).  
  44.                     setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)).  
  45.                     setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();  
  46.   
  47.     //https  
  48.     private static SSLConnectionSocketFactory socketFactory;  
  49.     private static TrustManager manager = new X509TrustManager() {  
  50.   
  51.         @Override  
  52.         public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {  
  53.   
  54.         }  
  55.   
  56.         @Override  
  57.         public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {  
  58.   
  59.         }  
  60.   
  61.         @Override  
  62.         public X509Certificate[] getAcceptedIssuers() {  
  63.             return null;  
  64.         }  
  65.     };  
  66.   
  67.     private static void enableSSL() {  
  68.         try {  
  69.             SSLContext sslContext = SSLContext.getInstance("TLS");  
  70.             sslContext.init(nullnew TrustManager[]{manager}, null);  
  71.             socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);  
  72.         } catch (NoSuchAlgorithmException e) {  
  73.             e.printStackTrace();  
  74.         } catch (KeyManagementException e) {  
  75.             e.printStackTrace();  
  76.         }  
  77.     }  
  78.   
  79.     /** 
  80.      * https get 
  81.      * @param url 
  82.      * @param data 
  83.      * @return 
  84.      * @throws IOException 
  85.      */  
  86.     public static CloseableHttpResponse doHttpsGet(String url, String data){  
  87.         enableSSL();  
  88.         Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()  
  89.                 .register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();  
  90.         PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);  
  91.         CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager)  
  92.                 .setDefaultRequestConfig(requestConfig).build();  
  93.         HttpGet httpGet = new HttpGet(url);  
  94.         CloseableHttpResponse response = null;  
  95.         try {  
  96.             response = httpClient.execute(httpGet, context);  
  97.         }catch (Exception e){  
  98.             e.printStackTrace();  
  99.         }  
  100.   
  101.         return response;  
  102.     }  
  103.   
  104.     /** 
  105.      * https post 
  106.      * @param url 
  107.      * @param values 
  108.      * @return 
  109.      * @throws IOException 
  110.      */  
  111.     public static CloseableHttpResponse doHttpsPost(String url, List<NameValuePair> values) {  
  112.         enableSSL();  
  113.         Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()  
  114.                 .register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();  
  115.         PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);  
  116.         CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager)  
  117.                 .setDefaultRequestConfig(requestConfig).build();  
  118.         HttpPost httpPost = new HttpPost(url);  
  119.         UrlEncodedFormEntity entity = new UrlEncodedFormEntity(values, Consts.UTF_8);  
  120.         httpPost.setEntity(entity);  
  121.         CloseableHttpResponse response = null;  
  122.         try {  
  123.             response = httpClient.execute(httpPost, context);  
  124.         }catch (Exception e){}  
  125.         return response;  
  126.     }  
  127.   
  128.     /** 
  129.      * http get 
  130.      * 
  131.      * @param url 
  132.      * @param data 
  133.      * @return 
  134.      */  
  135.     public static CloseableHttpResponse doGet(String url, String data) {  
  136.         CookieStore cookieStore = new BasicCookieStore();  
  137.         CloseableHttpClient httpClient = HttpClientBuilder.create().  
  138.                 setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()).  
  139.                 setRedirectStrategy(new DefaultRedirectStrategy()).  
  140.                 setDefaultCookieStore(cookieStore).  
  141.                 setDefaultRequestConfig(requestConfig).build();  
  142.   
  143.         HttpGet httpGet = new HttpGet(url);  
  144.         CloseableHttpResponse response = null;  
  145.         try {  
  146.             response = httpClient.execute(httpGet, context);  
  147.         }catch (Exception e){}  
  148.         return response;  
  149.     }  
  150.   
  151.     /** 
  152.      * http post 
  153.      * 
  154.      * @param url 
  155.      * @param values 
  156.      * @return 
  157.      */  
  158.     public static CloseableHttpResponse doPost(String url, List<NameValuePair> values) {  
  159.         CookieStore cookieStore = new BasicCookieStore();  
  160.         CloseableHttpClient httpClient = HttpClientBuilder.create().  
  161.                 setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()).  
  162.                 setRedirectStrategy(new DefaultRedirectStrategy()).  
  163.                 setDefaultCookieStore(cookieStore).  
  164.                 setDefaultRequestConfig(requestConfig).build();  
  165.   
  166.         HttpPost httpPost = new HttpPost(url);  
  167.         UrlEncodedFormEntity entity = new UrlEncodedFormEntity(values, Consts.UTF_8);  
  168.         httpPost.setEntity(entity);  
  169.         CloseableHttpResponse response = null;  
  170.         try {  
  171.             response = httpClient.execute(httpPost, context);  
  172.         }catch (Exception e){}  
  173.         return response;  
  174.     }  
  175.   
  176.   
  177.     /** 
  178.      * 直接把Response内的Entity内容转换成String 
  179.      * 
  180.      * @param httpResponse 
  181.      * @return 
  182.      */  
  183.     public static String toString(CloseableHttpResponse httpResponse) {  
  184.         // 获取响应消息实体  
  185.         String result = null;  
  186.         try {  
  187.             HttpEntity entity = httpResponse.getEntity();  
  188.             if (entity != null) {  
  189.                 result = EntityUtils.toString(entity,"UTF-8");  
  190.             }  
  191.         }catch (Exception e){}finally {  
  192.             try {  
  193.                 httpResponse.close();  
  194.             } catch (IOException e) {  
  195.                 e.printStackTrace();  
  196.             }  
  197.         }  
  198.         return result;  
  199.     }  
  200.   
  201.     public static void main(String[] args){  
  202.         CloseableHttpResponse response = HttpClientUtil.doHttpsGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxb2ebe42765aad029&secret=720661590f720b1f501ab3f390f80d52","");  
  203.         System.out.println(HttpClientUtil.toString(response));  
  204.     }  
  205. }  

AccessTokenResult:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public class AccessTokenResult implements Serializable{  
  2.     private static final long serialVersionUID = -5429222736793133180L;  
  3.     private String access_token;  
  4.     private int expires_in;  
  5.     private String refresh_token;  
  6.     private String openid;  
  7.     private String scope;  
  8.     private String unionid;  
  9.   
  10.     public String getAccess_token() {  
  11.         return access_token;  
  12.     }  
  13.   
  14.     public void setAccess_token(String access_token) {  
  15.         this.access_token = access_token;  
  16.     }  
  17.   
  18.     public int getExpires_in() {  
  19.         return expires_in;  
  20.     }  
  21.   
  22.     public void setExpires_in(int expires_in) {  
  23.         this.expires_in = expires_in;  
  24.     }  
  25.   
  26.     public String getRefresh_token() {  
  27.         return refresh_token;  
  28.     }  
  29.   
  30.     public void setRefresh_token(String refresh_token) {  
  31.         this.refresh_token = refresh_token;  
  32.     }  
  33.   
  34.     public String getOpenid() {  
  35.         return openid;  
  36.     }  
  37.   
  38.     public void setOpenid(String openid) {  
  39.         this.openid = openid;  
  40.     }  
  41.   
  42.     public String getScope() {  
  43.         return scope;  
  44.     }  
  45.   
  46.     public void setScope(String scope) {  
  47.         this.scope = scope;  
  48.     }  
  49.   
  50.     public String getUnionid() {  
  51.         return unionid;  
  52.     }  
  53.   
  54.     public void setUnionid(String unionid) {  
  55.         this.unionid = unionid;  
  56.     }  
  57.   
  58.     @Override  
  59.     public String toString() {  
  60.         return "AccessTokenResult{" +  
  61.                 "access_token='" + access_token + '\'' +  
  62.                 ", expires_in=" + expires_in +  
  63.                 ", refresh_token='" + refresh_token + '\'' +  
  64.                 ", openid='" + openid + '\'' +  
  65.                 ", scope='" + scope + '\'' +  
  66.                 ", unionid='" + unionid + '\'' +  
  67.                 '}';  
  68.     }  
  69. }  

ErrorInfoResult:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public class ErrorInfoResult implements Serializable{  
  2.     private static final long serialVersionUID = -7644965943068191814L;  
  3.   
  4.     private int errcode;  
  5.     private String errmsg;  
  6.   
  7.     public int getErrcode() {  
  8.         return errcode;  
  9.     }  
  10.   
  11.     public void setErrcode(int errcode) {  
  12.         this.errcode = errcode;  
  13.     }  
  14.   
  15.     public String getErrmsg() {  
  16.         return errmsg;  
  17.     }  
  18.   
  19.     public void setErrmsg(String errmsg) {  
  20.         this.errmsg = errmsg;  
  21.     }  
  22. }  

UserInfoResult:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public class UserInfoResult implements Serializable {  
  2.     private static final long serialVersionUID = 7897488657400830591L;  
  3.     private String openid;  
  4.     private String nickname;  
  5.     private String sex;  
  6.     private String province;  
  7.     private String city;  
  8.     private String country;  
  9.     private String headimgurl;  
  10.     private String unionid;  
  11.   
  12.     public String getUnionid() {  
  13.         return unionid;  
  14.     }  
  15.   
  16.     public void setUnionid(String unionid) {  
  17.         this.unionid = unionid;  
  18.     }  
  19.   
  20.     public String getHeadimgurl() {  
  21.         return headimgurl;  
  22.     }  
  23.   
  24.     public void setHeadimgurl(String headimgurl) {  
  25.         this.headimgurl = headimgurl;  
  26.     }  
  27.   
  28.     public String getCountry() {  
  29.         return country;  
  30.     }  
  31.   
  32.     public void setCountry(String country) {  
  33.         this.country = country;  
  34.     }  
  35.   
  36.     public String getCity() {  
  37.         return city;  
  38.     }  
  39.   
  40.     public void setCity(String city) {  
  41.         this.city = city;  
  42.     }  
  43.   
  44.     public String getProvince() {  
  45.         return province;  
  46.     }  
  47.   
  48.     public void setProvince(String province) {  
  49.         this.province = province;  
  50.     }  
  51.   
  52.     public String getSex() {  
  53.         return sex;  
  54.     }  
  55.   
  56.     public void setSex(String sex) {  
  57.         this.sex = sex;  
  58.     }  
  59.   
  60.     public String getNickname() {  
  61.         return nickname;  
  62.     }  
  63.   
  64.     public void setNickname(String nickname) {  
  65.         this.nickname = nickname;  
  66.     }  
  67.   
  68.     public String getOpenid() {  
  69.         return openid;  
  70.     }  
  71.   
  72.     public void setOpenid(String openid) {  
  73.         this.openid = openid;  
  74.     }  
  75.   
  76.     @Override  
  77.     public String toString() {  
  78.         return "UserInfoResult{" +  
  79.                 "openid='" + openid + '\'' +  
  80.                 ", nickname='" + nickname + '\'' +  
  81.                 ", sex='" + sex + '\'' +  
  82.                 ", province='" + province + '\'' +  
  83.                 ", city='" + city + '\'' +  
  84.                 ", country='" + country + '\'' +  
  85.                 ", headimgurl='" + headimgurl + '\'' +  
  86.                 ", unionid='" + unionid + '\'' +  
  87.                 '}';  
  88.     }  
  89. }  

WxConstants:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public class WxConstants {  
  2.     //appId;  
  3.     public final static String appId = "wxb2ebe42765aad029";  
  4.     //  
  5.     public final static String appSecret = "720661590f720b1f501ab3f390f80d52";  
  6. }  

WxUtil:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public class WxUtil {  
  2.     private static Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").disableHtmlEscaping().create();  
  3.     /** 
  4.      * 生成授权URL 
  5.      * @param callbackUrl 
  6.      * @return 
  7.      */  
  8.     public static String authorizeUrl(String callbackUrl){  
  9.         StringBuilder sb = new StringBuilder();  
  10.         try {  
  11.             sb.append("https://open.weixin.qq.com/connect/oauth2/authorize?appid=").  
  12.                     append(WxConstants.appId).  
  13.                     append("&redirect_uri=").  
  14.                     append(URLEncoder.encode(callbackUrl,"UTF-8")).  
  15.                     append("&response_type=code").  
  16.                     //append("&scope=snsapi_base ").  
  17.                     append("&scope=snsapi_userinfo").  
  18.                     append("&state=STATE").  
  19.                     append("#wechat_redirect");  
  20.         } catch (UnsupportedEncodingException e) {  
  21.             e.printStackTrace();  
  22.         }  
  23.   
  24.         return sb.toString();  
  25.     }  
  26.   
  27.     /** 
  28.      * 获取access_token 
  29.      * @param code 
  30.      * @return 
  31.      */  
  32.     public static AccessTokenResult accessToken(String code){  
  33.         AccessTokenResult accessTokenResult = null;  
  34.         StringBuilder sb = new StringBuilder();  
  35.         sb.append("https://api.weixin.qq.com/sns/oauth2/access_token?appid=").  
  36.                 append(WxConstants.appId).  
  37.                 append("&secret=").  
  38.                 append(WxConstants.appSecret).  
  39.                 append("&code=").  
  40.                 append(code).  
  41.                 append("&grant_type=authorization_code");  
  42.         String result = HttpClientUtil.toString(HttpClientUtil.doHttpsGet(sb.toString(), ""));  
  43.         if(result != null){  
  44.             accessTokenResult = gson.fromJson(result,AccessTokenResult.class);  
  45.         }  
  46.         return accessTokenResult;  
  47.     }  
  48.   
  49.     /** 
  50.      * refreshToken 重新获取 accessToken 
  51.      * @param refreshToken 
  52.      * @return 
  53.      */  
  54.     public static AccessTokenResult refreshToken(String refreshToken){  
  55.         AccessTokenResult accessTokenResult = null;  
  56.         StringBuilder sb = new StringBuilder();  
  57.         sb.append("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=").  
  58.                 append(WxConstants.appId).  
  59.                 append("&refresh_token=").  
  60.                 append(refreshToken).  
  61.                 append("&grant_type=refresh_token");  
  62.         String result = HttpClientUtil.toString(HttpClientUtil.doHttpsGet(sb.toString(), ""));  
  63.         if(result != null){  
  64.             accessTokenResult = gson.fromJson(result,AccessTokenResult.class);  
  65.         }  
  66.         return accessTokenResult;  
  67.     }  
  68.   
  69.     /** 
  70.      * 获取用户信息 需要snstype 为 userinfo 非 base 
  71.      * @param accessToken 
  72.      * @param openId 
  73.      * @return 
  74.      */  
  75.     public static UserInfoResult userInfo(String accessToken,String openId){  
  76.         UserInfoResult userInfoResult = null;  
  77.         StringBuilder sb = new StringBuilder();  
  78.         sb.append("https://api.weixin.qq.com/sns/userinfo?access_token=").  
  79.                 append(accessToken).  
  80.                 append("&openid=").  
  81.                 append(openId).  
  82.                 append("&lang=zh_CN");  
  83.         String result = HttpClientUtil.toString(HttpClientUtil.doHttpsGet(sb.toString(), ""));  
  84.         if(result != null){  
  85.             userInfoResult = gson.fromJson(result,UserInfoResult.class);  
  86.         }  
  87.         return userInfoResult;  
  88.     }  
  89.   
  90.     /** 
  91.      * 判断accesstoken 是否有效 
  92.      * @param accessToken 
  93.      * @param openId 
  94.      * @return 
  95.      */  
  96.     public static boolean authAccessToken(String accessToken,String openId){  
  97.         ErrorInfoResult errorInfoResult = null;  
  98.         boolean isValid = false;  
  99.         StringBuilder sb = new StringBuilder();  
  100.         sb.append("https://api.weixin.qq.com/sns/auth?access_token=").  
  101.                 append(accessToken).  
  102.                 append("&openid=").  
  103.                 append(openId);  
  104.         String result = HttpClientUtil.toString(HttpClientUtil.doHttpsGet(sb.toString(), ""));  
  105.         if(result != null){  
  106.             errorInfoResult = gson.fromJson(result,ErrorInfoResult.class);  
  107.             if(0 == errorInfoResult.getErrcode()){  
  108.                 isValid = true;  
  109.             }  
  110.         }  
  111.         return isValid;  
  112.     }  
  113.   
  114.     public static void main(String[] args){  
  115.         String url = WxUtil.authorizeUrl("http://zszs.ngrok.cc/index.jsp");  
  116.         System.out.println(url);  
  117.   
  118.         System.out.println(HttpClientUtil.toString(HttpClientUtil.doGet("http://dpcola2.ngrok.cc/activityvip/customized/externalColaDrawLottery?activity=03D39BCAF4AAC406&prizePackage=FAB7B93B21645FAC&_dpKey=2656cola1455875399784&phoneNum=13917114404","")));  
  119.     }  
  120. }  





1 0
原创粉丝点击