Many people on the internet use Sina API to develop Sina Weibo clients and encounter the problem of being unable to send images. Many people are stuck in this forum. NowCodePresented, hoping to help some friends.
/**
* Posting Weibo posts with images
* @ 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 ";
String PIC = "\ r \ n --" + boundary + "\ r \ ncontent-Disposition: Form-data; name = \" pic \"; filename = \ "image.jpg \" \ r \ ncontent-type: image/JPEG \ r \ n "; arrears
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); // you can specify the form type and delimiter.
Request. setrequestproperty ("Content-Length", String. valueof (content. getbytes (). length + status. getbytes (). length + pic. getbytes (). length + afile. length () + end_data.length); // you can specify the 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 (200 = request. getresponsecode ()){
Result = "success ";
}
} Catch (filenotfoundexception E1 ){
E1.printstacktrace ();
} Catch (ioexception e ){
E. printstacktrace (); Women's brand rankings
} Catch (oauthmessagesignerexception e ){
E. printstacktrace ();
} Catch (oauthexpectationfailedexception e ){
E. printstacktrace ();
} Catch (oauthcommunicationexception e ){
E. printstacktrace ();
}
Return result;
}