栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java实现新浪微博Oauth接口发送图片和文字的方法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java实现新浪微博Oauth接口发送图片和文字的方法

本文实例讲述了java实现新浪微博Oauth接口发送图片和文字的方法。分享给大家供大家参考。具体如下:

基于网上很多人利用新浪api开发新浪微博客户端的时候遇到无法发图片的问题,很多人卡在了这一布。现将代码呈上,希望能帮到一些朋友。


public String uploadStatus(String token, String tokenSecret, File aFile, String status, String urlPath) {
  httpOAuthConsumer = new DefaultOAuthConsumer(consumerKey,consumerSecret);
  httpOAuthConsumer.setTokenWithSecret(token,tokenSecret);
  String result = null;
  try {
   URL url = new URL(urlPath);
   HttpURLConnection request = (HttpURLConnection) url.openConnection();
   request.setDoOutput(true);
   request.setRequestMethod("POST");
   HttpParameters para = new HttpParameters();
   para.put("status", URLEncoder.encode(status,"utf-8").replaceAll("\+", "%20"));
   String boundary = "---------------------------37531613912423";
   String content = "--"+boundary+"rnContent-Disposition: form-data; name="status"rnrn";
   String pic = "rn--"+boundary+"rnContent-Disposition: form-data; name="pic"; filename="image.jpg"rnContent-Type: image/jpegrnrn";
   byte[] end_data = ("rn--" + boundary + "--rn").getBytes();
   FileInputStream stream = new FileInputStream(aFile);
   byte[] file = new byte[(int) aFile.length()];
   stream.read(file);
   request.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary); //设置表单类型和分隔符
   request.setRequestProperty("Content-Length", String.valueOf(content.getBytes().length + status.getBytes().length + pic.getBytes().length + aFile.length() + end_data.length)); //设置内容长度
   httpOAuthConsumer.setAdditionalParameters(para);
   httpOAuthConsumer.sign(request);
   OutputStream ot = request.getOutputStream();
   ot.write(content.getBytes());
   ot.write(status.getBytes());
   ot.write(pic.getBytes());
   ot.write(file);
   ot.write(end_data);
   ot.flush();
   ot.close();
   request.connect();
   if (200 == request.getResponseCode()) {
    result = "SUCCESS";
   }
  } catch (FileNotFoundException e1) {
   e1.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (OAuthMessageSignerException e) {
   e.printStackTrace();
  } catch (OAuthExpectationFailedException e) {
   e.printStackTrace();
  } catch (OAuthCommunicationException e) {
   e.printStackTrace();
  }
  return result;
}

希望本文所述对大家的java程序设计有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/151444.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号