吐槽:微信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. thinkphp3.2 代码生成并点击验证码

    本人小菜鸟一仅仅.为了自我学习和交流PHP(jquery,linux,lamp,shell,javascript,server)等一系列的知识.小菜鸟创建了一个群.希望光临本博客的人能够进来交流.寻求 ...

  2. 手把手教你如何加入到github的开源世界! (转)

    我曾经一直想加入到开源项目中,但是因为没有人指导流程,网上看了很多,基本都是说了个大概,如果你也是一个初出茅庐的人,那么,我将以自己提交的一次开源代码为例,教会你步入开源的世界. 1,首先登陆到htt ...

  3. SQL Server 2005------函数

    原文:SQL Server 2005------函数 SQL Server 2005支持用户自定义函数和内置系统函数,根据返回值类型又分为标量函数和表值函数. 1.标量函数标量函数:返回单个数据值,返 ...

  4. 修改Hosts不生效的一个场景-web(转)

    Update: 如果浏览器使用了代理工具,修改 Hosts 也不会生效.这里是因为,浏览器会优先考虑代理工具(如添加 pac 文件.SwitchySharp等)的代理,建议调试的时候先关闭这些代理. ...

  5. Android 在非主线程无法操作UI意识

    Android在应用显示Dialog是一个非常easy事儿,但我从来没有尝试过Service里面展示Dialog. 经验UI操作要在主线程,本地的服务Service是主线程里没错,可是远程servic ...

  6. Java多线程之Lock的使用(转)

    package thread.lock; import java.util.concurrent.ExecutorService; import java.util.concurrent.Execut ...

  7. B/S 类项目改善

    B/S 类项目改善的一些建议   要分享的议题 性能提升:在访问量逐渐增大的同时,如何增大单台服务器的 PV2 上限,增加 TPS3 ? RESTful:相较于传统的 SOAP1,RESTful 风格 ...

  8. JavaScript中null和undefined的总结

    先说null,它表示一个特殊值,常用来描述“空值”.对null执行typeof运算,结果返回字符串“object”,也就是说,可以将null认为是一个特殊的对象值,含义是“非对象”(感觉怪怪的).实际 ...

  9. Linux(CentOS)系统下安装好apache(httpd)服务后,其他电脑无法访问的原因

    原文:Linux(CentOS)系统下安装好apache(httpd)服务后,其他电脑无法访问的原因 今天试了下在虚拟机上利用CentOS系统的yum命令安装好了httpd(apache2.4.6), ...

  10. Linux下的变化的主机名步骤

    Linux下变化的主机名gpdb 步骤1.执行vi /etc/sysconfig/network命令 NETWORKING=yesHOSTNAME=gpdb 第二步.执行hostname gpdb令 ...