java调⽤公众平台接⼝(⼀)
公众平台
这两天在⽹上看了其他的⽅法,也调试了⼀些,然后⾃⼰整理了⼀下,⽅便⾃⼰学习,也⽅便⼤家使⽤。
调⽤接⼝
1、java调⽤上传图⽚接⼝
public final static String IMAGE = "api.weixin.qq/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN";
public static String uploadimg(MultipartFile file ) {
CloseableHttpClient client = ateDefault();
// 创建httppost
String requestUrl = place("ACCESS_TOKEN", access_token);//替换调access_token
HttpPost post = new HttpPost(requestUrl);
RequestConfig config = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(20000).build();
post.setConfig(config);
File f = null;
try {
f = new OriginalFilename());
InputStream(),f);
} catch (IOException e) {
e.printStackTrace();
}
String name = f.getName();
FileBody fileBody = new FileBody(f, ContentType.DEFAULT_BINARY,name);
String filename = Filename();
long contentLength = ContentLength();
ContentType contentType = ContentType();
MultipartEntityBuilder builder = ate();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("media", fileBody);
// 相当于 <input type="file" class="file" name="file">,匹配@RequestParam("file")
// .addPart()可以设置模拟浏览器<input/>的表单提交
HttpEntity entity = builder.build();
post.setEntity(entity);
String result = "";
try {
CloseableHttpResponse e = ute(post);
HttpEntity resEntity = e.getEntity();
if(entity != null) {
result = String(resEntity);
System.out.println("response content:" + result);
}
} catch (IOException var10) {
System.out.println("请求解析验证码io异常    "+var10);
/
/("请求解析验证码io异常",var10);
var10.printStackTrace();
}
return result;
}
public static void inputStreamToFile(InputStream ins, File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ad(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
2、新增永久图⽚素材
只需要修改 requestUrl
public final static String ADD_MATERIAL_IMAGE = "api.weixin.qq/cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=TYPE";
3、新增永久视频素材
public final static String ADD_MATERIAL_IMAGE = "api.weixin.qq/cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=TYPE"; /**
* 上传永久素材(除图⽂)
* @param    file
* @param    type
* @param    title type为video时需要,其他类型设null
* @param    introduction type为video时需要,其他类型设null
* @return    {"media_id":MEDIA_ID,"url":URL}
*/
public static String uploadPermanentMaterial(File file, String type, String title, String introduction) {
String url = ADD_place("ACCESS_TOKEN", access_token).replace("TYPE", type);// 替换调access_token
String result = null;
try {
URL uploadURL = new URL(url);
HttpURLConnection conn = (HttpURLConnection) uploadURL.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Cache-Control", "no-cache");
String boundary = "-----------------------------" + System.currentTimeMillis();
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
OutputStream output = OutputStream();
output.write(("--" + boundary + "\r\n").getBytes());
output.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"%s\"\r\n", Name()).getBytes());
output.write("Content-Type: video/mp4 \r\n\r\n".getBytes());
byte[] data = new byte[1024];
int len = 0;
FileInputStream input = new FileInputStream(file);
while ((len = ad(data)) > -1) {
output.write(data, 0, len);
}
/*对类型为video的素材进⾏特殊处理*/
if ("video".equals(type)) {
output.write(("--" + boundary + "\r\n").getBytes());
output.write("Content-Disposition: form-data; name=\"description\";\r\n\r\n".getBytes());
output.write(String.format("{\"title\":\"%s\", \"introduction\":\"%s\"}", title, introduction).getBytes());
}
output.write(("\r\n--" + boundary + "--\r\n\r\n").getBytes());
代码转换output.flush();
output.close();
input.close();
InputStream resp = InputStream();
StringBuffer sb = new StringBuffer();
while ((len = ad(data)) > -1)
sb.append(new String(data, 0, len, "utf-8"));
resp.close();
result = sb.toString();
} catch (IOException e) {
//....
}
return result;
}
上传视频的这个⽅法也可以上传其他素材。
4、上传永久图⽂素材
⾸先考虑传值,官⽅的⽰例
{
"articles": [{
"title": TITLE,
"thumb_media_id": THUMB_MEDIA_ID,
"author": AUTHOR,
"digest": DIGEST,
"show_cover_pic": SHOW_COVER_PIC(0 / 1),
"content": CONTENT,
"content_source_url": CONTENT_SOURCE_URL,
"need_open_comment":1,
"only_fans_can_comment":1
},
//若新增的是多图⽂素材,则此处应还有⼏段articles结构
]
}
1、直接put json,下⾯是⼀个简单的例⼦。这样很容易完成⽰例
//{  "tag":{ "id":134,//标签id "name":"⼴东"  } }
JSONObject json1 = new JSONObject();
json1.put("name", "⼴东");
JSONObject json = new JSONObject();
json.put("tag", json1);
2、使⽤实体类,可以参数与json转换
/*获取素材列表参数实体类**/
public class AddNewsParam {
private Articles [] articles;
public class Articles {
private String title;// 图⽂消息的标题
private String thumb_media_id;// 图⽂消息的封⾯图⽚素材id(必须是永久mediaID)
private String author;// 作者
private String digest;// 图⽂消息的摘要,仅有单图⽂消息才有摘要,多图⽂此处为空
private Integer show_cover_pic;// 是否显⽰封⾯,0为false,即不显⽰,1为true,即显⽰
private String content;// 图⽂消息的具体内容,⽀持HTML标签,必须少于2万字符,⼩于1M,且此处会去除JS private String content_source_url;// 图⽂消息的原⽂地址,即点击“阅读原⽂”后的URL
private Integer need_open_comment;// 图⽂页的URL,或者,当获取的列表是图⽚素材列表时,该字段是图⽚的URL private Integer only_fans_can_comment;// Uint32 是否粉丝才可评论,0所有⼈可评论,1粉丝才可评论
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getThumb_media_id() {
return thumb_media_id;
}
public void setThumb_media_id(String thumb_media_id) {
this.thumb_media_id = thumb_media_id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getDigest() {
return digest;
}
public void setDigest(String digest) {
this.digest = digest;
}
public Integer getShow_cover_pic() {
return show_cover_pic;
}
public void setShow_cover_pic(Integer show_cover_pic) {
this.show_cover_pic = show_cover_pic;
}
public String getContent() {
return content;
}
public void setContent(String content) {
}
public String getContent_source_url() {
return content_source_url;
}
public void setContent_source_url(String content_source_url) {
}
public Integer getNeed_open_comment() {
return need_open_comment;
}
public void setNeed_open_comment(Integer need_open_comment) {
}
public Integer getOnly_fans_can_comment() {
return only_fans_can_comment;
}
public void setOnly_fans_can_comment(Integer only_fans_can_comment) {
}
}
public Articles[] getArticles() {
return articles;
}
public void setArticles(Articles[] articles) {
this.articles = articles;
}
}
调⽤⽅法
/**上传图⽂素材
* @param accessToken
* @return
*/
public static String addNews(String accessToken,AddNewsParam entity) {
String result = null;
String requestUrl = place("ACCESS_TOKEN", accessToken);//替换调access_token
String outputStr ;
JSONObject jsonObject = new JSONObject();
jsonObject = JSONObject.fromObject(entity);
outputStr = String();//将参数对象转换成json字符串
System.out.println(outputStr);
jsonObject = httpsRequest(requestUrl, "POST", outputStr);  //发送https请求(请求的路径,⽅式,所携带的参数)
// 如果请求成功
if (null != jsonObject) {
try {
result = String();
System.out.println(jsonObject);
} catch (JSONException e) {
accessToken = null;
// 获取Material失败
result = (Int("errcode")+","+String("errmsg"));
System.out.println("Int(errcode)"+Int("errcode"));
System.out.println("String(errmsg)"+String("errmsg"));
<("获取Material失败 errcode:{} errmsg:{}", Int("errcode"), String("errmsg"));              }
}
return result;
}
如果⽤第⼀种⽅式,直接传json,修改⼀下代码就可以使⽤。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。