使用gson和httpclient呼叫微信公众平台API

时间:2023-03-08 18:59:08

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

不好意思,昨天晚上发表文章,****老失败。

导致只有一个标题。

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