java实现新浪微博Oauth接口发送图片和文字的方法
本文实例讲述了java实现新浪微博Oauth接口发送图片和文字的方法。分享给大家供大家参考。具体如下:
基于网上很多人利用新浪api开发新浪微博客户端的时候遇到无法发图片的问题,很多人卡在了这一布。现将代码呈上,希望能帮到一些朋友。
/**
*发表带图片的微博
*@paramtoken
*@paramtokenSecret
*@paramaFile
*@paramstatus
*@paramurlPath
*@return
*/
publicStringuploadStatus(Stringtoken,StringtokenSecret,FileaFile,Stringstatus,StringurlPath){
httpOAuthConsumer=newDefaultOAuthConsumer(consumerKey,consumerSecret);
httpOAuthConsumer.setTokenWithSecret(token,tokenSecret);
Stringresult=null;
try{
URLurl=newURL(urlPath);
HttpURLConnectionrequest=(HttpURLConnection)url.openConnection();
request.setDoOutput(true);
request.setRequestMethod("POST");
HttpParameterspara=newHttpParameters();
para.put("status",URLEncoder.encode(status,"utf-8").replaceAll("\\+","%20"));
Stringboundary="---------------------------37531613912423";
Stringcontent="--"+boundary+"\r\nContent-Disposition:form-data;name=\"status\"\r\n\r\n";
Stringpic="\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();
FileInputStreamstream=newFileInputStream(aFile);
byte[]file=newbyte[(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);
OutputStreamot=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(FileNotFoundExceptione1){
e1.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}catch(OAuthMessageSignerExceptione){
e.printStackTrace();
}catch(OAuthExpectationFailedExceptione){
e.printStackTrace();
}catch(OAuthCommunicationExceptione){
e.printStackTrace();
}
returnresult;
}
希望本文所述对大家的java程序设计有所帮助。