zoukankan      html  css  js  c++  java
  • 使用gson和httpclient呼叫微信公众平台API

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

    导致只有一个标题。

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

  • 相关阅读:
    在插入一条记录后 取得自动增长ID
    hashtable,dictionary 从原理上说说有什么异同,哪个性能高一些
    单例模式
    聚簇索引与非聚簇索引的区别
    基于SQL SERVER2008的SCCM2007部署
    XML架构下的表结构设置主键
    IE6与IE7下一点样式的区别
    Session丢失原因与解决方案小结
    Python_如何去除字符串里的空格
    Python_让人脑阔疼的编码问题(转)+(整理)
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/4740755.html
Copyright © 2011-2022 走看看