This article describes the Java implementation of Sina Weibo OAuth interface to send pictures and text methods. Share to everyone for your reference. Specifically as follows:
Based on the Internet many people use the Sina API to develop Sina Weibo client when the problem is not able to send pictures, a lot of people stuck in this cloth. Now put the code, hoping to help some friends.
/** * @param token * @param tokensecret * @param afile * @param status * @param urlpath * @return/public St Ring 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); Set the form type and separator request.setrequestproperty ("Content-length", String.valueof (Content.getbytes (). Length + Status.getbytes (). Length + pic.getbytes (). Length + afile.length () + end_data.length));
Set content 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 (= = = 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;
}
I hope this article will help you with your Java programming.