我自己在公司第一次接触微信公众号,有很多的不熟悉。查了很多的资料。看了微信开发的官方文档。但是微信的官方文档是php版的。可怜我php虽然学过一点。但是都交给了我的老师,深感惭愧。不过还好网络上的一位大牛写了java版的微信开发。其中的一个https封装我感觉有点繁琐。又根据自己的能力和网上的相关例子该进了一下。希望对有需要的有一些帮助。大牛的博客链接:http://www.cnblogs.com/liuhongfeng/p/4846260.html
1.因为微信的一些接口的访问是https的链接。证书的访问是我们需要解决的问题。我们采用忽略证书,信任所有的证书来封装一个方法;
//https信任所有请求创建
public static CloseableHttpClient createSSLClientDefault(){
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
//信任所有
public boolean isTrusted(X509Certificate[] chain,
String authType) {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}
2.我们根据微信的接口来封装数据,
url:我们请求的url比如:
// 菜单创建(POST) 限100(次/天)
public static String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
method:get或者post
data:我们post请求所要携带的数据请求,
最后我们返回的是json的数据格式。这样就可以进行https的请求了
/**
* 发送Https请求并获取结果
* @param requestUrl
* @param method
* @param data
* @return
*/
public static JSONObject httpRequset(String url,String method,String data){
CloseableHttpResponse responeOne=null;
HttpUriRequest httpUriRequest=null;
JSONObject jsonObject=null;
HttpPost httpPost=null;
StringBuffer stringBuffer=new StringBuffer();
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
CloseableHttpClient client=createSSLClientDefault();
if(method.equals("GET")){
httpUriRequest=new HttpGet(url);
}
if(data!=null){
httpPost=new HttpPost(url);
jsonObject=JSONObject.fromObject(data);
StringEntity entityString = new StringEntity(jsonObject.toString(),"utf-8");//解决中文乱码问题
httpPost.setEntity(entityString);
}
try {if(httpUriRequest!=null){
responeOne= client.execute(httpUriRequest);
}else{
responeOne= client.execute(httpPost);
}
responeOne.setHeader("Content-Type", "application/json");
HttpEntity entity=responeOne.getEntity();
InputStream in = entity.getContent();
String jsonContent=IOUtils.toString(in, "utf-8");
jsonObject=JSONObject.fromObject(jsonContent);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonObject;
}
谢谢你的观看,希望能帮助到你。转载请注明出处。