吐槽:微信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老失败。

导致只有一个标题。

版权声明:本文博客原创文章,博客,未经同意,不得转载。

使用gson和httpclient呼叫微信公众平台API的更多相关文章

  1. 微信公众平台API接口

    简介 微信公众平台消息接口为开发者提供了一种新的消息处理方式.微信公众平台消息接口为开发者提供与用户进行消息交互的能力.对于成功接入消息接口的微信公众账号,当用户发消息给公众号,微信公众平台服务器会使 ...

  2. Senparc.Weixin.MP SDK 微信公众平台开发教程(四):Hello World

    =============  以下写于2013-07-20 ============= 这一篇文章其实可以写在很前面,不过我还是希望开发者们尽多地了解清楚原理之后再下手. 通过上一篇Senparc.W ...

  3. 微信公众平台Php版php开发(转)

    http://www.1990c.com/?p=932 近在做微信公众平台开发,一口气写了二十几个功能,挺有意思的-  今天来分享一下开发经验~微信公众平台提供的接口很简单,先看看消息交互流程:  说 ...

  4. 微信公众平台开发(免费云BAE+高效优雅的Python+网站开放的API)

    虽然校园App是个我认为的绝对的好主意,但最近有个也不错的营销+开发的模式出现:微信平台+固定域名服务器. 微信公众平台的运行模式不外两个: 一.机器人模式或称转发模式,将说话内容转发到服务器上完成, ...

  5. 转载收藏之用 - 微信公众平台开发教程(四):Hello World

    这一篇文章其实可以写在很前面,不过我还是希望开发者们尽多地了解清楚原理之后再下手. 通过上一篇Senparc.Weixin.MP SDK 微信公众平台开发教程(三):微信公众平台开发验证,我们已经使微 ...

  6. 微信公众平台PHP开发

    p=932" style="color: rgb(255, 153, 0); text-decoration: none;">微信公众平台PHP开发 2013.05 ...

  7. 微信公众平台开发框架 Bee.WeiXin

    我们来看一下如何通过Bee.WeiXin开发微信公众平台.关于微信公众平台的一般性介绍, 这里不做展开. 园里找一找就可以了. 本文主要是介绍Bee.WeXin, 代码已发布到https://beew ...

  8. 微信公众平台消息接口开发(12)消息接口Bug

    微信公众平台开发模式 微信公众平台消息接口 微信公众平台API 微信开发模式 Bug 方倍工作室 原文:http://www.cnblogs.com/txw1958/archive/2013/03/1 ...

  9. 微信公众平台.net HttpClient 异步客户端

    微信公众平台.net HttpClient 异步客户端 该客户端实现了对微信公众平台的后台管理,包括获取Token,发生客服消息(文本,图片,语音,视频),自定义菜单的创建,查询,删除,查询订阅用户, ...

随机推荐

  1. 【剑指offer】打印1到最大的n数字

    转载请注明出处:http://blog.csdn.net/ns_code/article/details/25562105 剑指offer第12题.九度OJ測试通过. 题目描写叙述: 给定一个数字N, ...

  2. Java Web整合开发(16) -- Struts 2.x 概述

    Struts2与Spring的整合 •Struts2框架为配合与Spring3框架进行整合,提供了相应的拦截器. •该组件名为StrutsSpringObjectFactory,位于struts2-s ...

  3. C++在设计和使用智能指针

    为一个C++用户的.使用指针可以算的上是常态,但在使用过程中.多的时间,可能是由于new要么malloc对象,上次忘记的释放结束(我会犯这样一个错误).内存泄露. 而此时智能指针可能能够帮助我去解决问 ...

  4. Java多线程总结之由synchronized说开去(转)

    这几天不断添加新内容,给个大概的提纲吧,方面朋友们阅读,各部分是用分割线隔开了的: synchronized与wait()/notify() JMM与synchronized ThreadLocal与 ...

  5. 推荐系统相关算法:SVD

    假如要预测Zero君对一部电影M的评分,而手上只有Zero君对若干部电影的评分和风炎君对若干部电影的评分(包含M的评分).那么能预测出Zero君对M的评分吗?答案显然是能.最简单的方法就是直接将预测分 ...

  6. Json.Net6.0入门学习试水篇

    原文:Json.Net6.0入门学习试水篇 前言 JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.简单地说,JSON 可以将 JavaScript 对象中 ...

  7. uva 1534 - Taekwondo(dp+馋)

    题目连接:uva 1534 - Taekwondo 题目大意:有两组什么东西,题目背景有点忘记了,就是给出两组数,两组个数分别为n,m,要求找出min(n,m)对数.每一个数最多最多选一次,使得这mi ...

  8. Unity3D流行的游戏开发人员构建高速检查站系统

    好友,大家好,欢迎关注我的博客.我是秦培,我的博客地址blog.csdn.net/qinyuanpei. 今天,我想分享的是,现在在移动平台上的检查点系统更受欢迎,机游戏如<愤慨的小鸟>. ...

  9. 解决cocos2d-x-3.1.1新androidproject

    下了个cocos2d-x-3.1.1,依照官方文档一步步配置win7下cocos2d-x-3.1.1的android开发环境,结果没有找到create_project.py这个文件.. 现将具体配置步 ...

  10. uva 10228 - Star not a Tree?(模拟退火)

    题目链接:uva 10228 - Star not a Tree? 题目大意:给定若干个点,求费马点(距离全部点的距离和最小的点) 解题思路:模拟退火算法,每次向周围尝试性的移动步长,假设发现更长处, ...