欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-03-04 17:11:41
本文实例讲述了java实现新浪微博oauth接口发送图片和文字的方法。分享给大家供大家参考。具体如下: 基于网上很多人利用新浪api开发新浪微博客户端的时候遇到无法发图片...

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

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

/**
* 发表带图片的微博
* @param token
* @param tokensecret
* @param afile
* @param status
* @param urlpath
* @return
*/
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+"\r\ncontent-disposition: form-data; name=\"status\"\r\n\r\n";
   string pic = "\r\n--"+boundary+"\r\ncontent-disposition: form-data; name=\"pic\"; filename=\"image.jpg\"\r\ncontent-type: image/jpeg\r\n\r\n";
   byte[] end_data = ("\r\n--" + boundary + "--\r\n").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程序设计有所帮助。