码迷,mamicode.com
首页 > 微信 > 详细

用gson和httpclient调用微信公众平台API

时间:2014-04-28 21:51:47      阅读:3509      评论:0      收藏:0      [点我收藏+]

标签:class   java   代码   文件   int   Go   c   os   数据   

吐槽:微信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

标签:class   java   代码   文件   int   Go   c   os   数据   

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!