用gson和httpclient调用微信公众平台API
来源:互联网 发布:什么是网络成瘾综合症 编辑:程序博客网 时间:2024/05/04 22:17
吐槽:微信api很无语,部分用xml,部分用json。
最近在找如何调用微信公众平台关于json相关的api比较方便,最后发现httpcliect和gson不错。如果你有更好的方式,请告诉我。
以下代码先了解如何使用gson和httpclient,有功夫再整到我的sophia里,呵呵。
import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.Reader;import java.util.HashMap;import java.util.Map;import org.apache.http.Consts;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.StatusLine;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpResponseException;import org.apache.http.client.ResponseHandler;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.entity.ContentType;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;import com.google.gson.Gson;import com.google.gson.GsonBuilder;import com.google.gson.JsonObject;public class JsonTest {/** * 获取access token * @return * @throws ClientProtocolException * @throws IOException */public static String getToken() throws ClientProtocolException, IOException {CloseableHttpClient httpclient = HttpClients.createDefault();//String appid = "eeeeeeee";String secret = "eeeeeeeeeeeeeeee";HttpGet httpget = new HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret) ;ResponseHandler<JsonObject> rh = new ResponseHandler<JsonObject>() { @Override public JsonObject handleResponse( final HttpResponse response) throws IOException { StatusLine statusLine = response.getStatusLine(); HttpEntity entity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { throw new HttpResponseException( statusLine.getStatusCode(), statusLine.getReasonPhrase()); } if (entity == null) { throw new ClientProtocolException("Response contains no content"); } Gson gson = new GsonBuilder().create(); //ContentType contentType = ContentType.getOrDefault(entity); //Charset charset = contentType.getCharset(); Reader reader = new InputStreamReader(entity.getContent()); return gson.fromJson(reader, JsonObject.class); }};JsonObject myjson = httpclient.execute(httpget, rh);System.out.println(myjson.get("access_token").getAsString());return myjson.get("access_token").getAsString();}/** * 下载文件 * @throws ClientProtocolException * @throws IOException */public static void downloadMediaFile(String token) throws ClientProtocolException, IOException {String mediaId = "fdsddddddddddd";String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";url = url.replaceAll("ACCESS_TOKEN", token);url = url.replaceAll("MEDIA_ID", mediaId);CloseableHttpClient httpclient = HttpClients.createDefault();HttpGet httpget = new HttpGet(url);CloseableHttpResponse response = httpclient.execute(httpget);try { HttpEntity entity = response.getEntity(); if (entity != null) { long len = entity.getContentLength(); if (len != -1) { byte[] content = EntityUtils.toByteArray(entity); System.out.println(response.getStatusLine()); OutputStream os = new FileOutputStream("/Users/sssss/abc.jpg");// 开始读取 os.write(content);// 完毕,关闭所有链接os.close(); } else { // Stream content out } }} finally { response.close();}}/** * post json格式数据包 ----- 客服消息 * @param map * @throws ClientProtocolException * @throws IOException */public static void postJsonData(Map map) throws ClientProtocolException, IOException {String token = "lv3s0iunvVvEj9K3bz12xofvXfW1916ePLqZ7mN6mx7reY-IDzPTrwoErd4pSMD4eSps56QbmbaQ";String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=ACCESS_TOKEN";url = url.replaceAll("ACCESS_TOKEN", token);CloseableHttpClient httpclient = HttpClients.createDefault();Gson gson = new Gson();StringEntity entity = new StringEntity(gson.toJson(map), ContentType.create("plain/text", Consts.UTF_8));entity.setChunked(true);HttpPost httppost = new HttpPost(url);httppost.setEntity(entity);CloseableHttpResponse response = httpclient.execute(httppost);System.out.println(response.getStatusLine());} public static void main(String[] args) throws ClientProtocolException, IOException {String token = getToken();downloadMediaFile(token);//客服消息Map map = new HashMap();map.put("touser", "o3Y0et021tT_MVK2bdY1DhSWwFCc");map.put("msgtype", "text");Map m = new HashMap();m.put("content", "hello world");map.put("text", m);postJsonData(map);}}
不好意思,昨天晚上发表文章,csdn老失败。导致只有标题。
0 0
- 用gson和httpclient调用微信公众平台API
- 微信公众平台api的Java调用
- 微信公众平台 天气查询功能 api调用
- 微信公众平台API
- 用 Rails 搭建微信公众平台 API
- 微信公众平台Js API WeixinApi
- 微信公众平台接口API
- 调用微信公众平台API免费给自己发消息
- PHP7.0微信公众平台开发3: API接口的调用代码模板
- 微信公众平台Js API实现微信分享
- php微信公众平台开发--接入微信API
- 微信公众平台
- 微信公众平台
- 微信公众平台
- 微信公众平台
- 微信公众平台
- 微信公众平台
- 微信公众平台
- 驱动开发的需要做的三件事
- 黑马程序员——学习日记4 java相关常用算法
- 黑马程序员-java基础学习笔记第二篇
- ubuntu环境变量设置
- vs2010调试小技巧
- 用gson和httpclient调用微信公众平台API
- Eclipse启动一闪而过
- 黑马程序员-java基础学习笔记第二篇
- C++ 调用JS
- html中title属性换行
- Linux下Mantis 安装配置手册
- java程序员面试交流项目经验
- html中title属性换行
- vs2010调试小技巧