java實現(xiàn)新浪微博Oauth接口發(fā)送圖片和文字的方法
更新時間:2015年07月14日 17:45:46 作者:鑒客
這篇文章主要介紹了java實現(xiàn)新浪微博Oauth接口發(fā)送圖片和文字的方法,涉及java調(diào)用新浪微博Oauth接口的使用技巧,具有一定參考接借鑒價值,需要的朋友可以參考下
本文實例講述了java實現(xiàn)新浪微博Oauth接口發(fā)送圖片和文字的方法。分享給大家供大家參考。具體如下:
基于網(wǎng)上很多人利用新浪api開發(fā)新浪微博客戶端的時候遇到無法發(fā)圖片的問題,很多人卡在了這一布?,F(xiàn)將代碼呈上,希望能幫到一些朋友。
/** * 發(fā)表帶圖片的微博 * @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); //設(shè)置表單類型和分隔符 request.setRequestProperty("Content-Length", String.valueOf(content.getBytes().length + status.getBytes().length + pic.getBytes().length + aFile.length() + end_data.length)); //設(shè)置內(nèi)容長度 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程序設(shè)計有所幫助。
相關(guān)文章
java線程Thread.sleep()對比對象的wait示例解析
這篇文章主要為大家介紹了java線程Thread.sleep()對比對象的wait示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-09-09MyBatis查詢數(shù)據(jù),賦值給List集合時,數(shù)據(jù)缺少的問題及解決
這篇文章主要介紹了MyBatis查詢數(shù)據(jù),賦值給List集合時,數(shù)據(jù)缺少的問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01詳解Spring Boot配置使用Logback進(jìn)行日志記錄的實戰(zhàn)
本篇文章主要介紹了詳解Spring Boot配置使用Logback進(jìn)行日志記錄的實戰(zhàn),具有一定的參考價值,有興趣的朋友可以了解一下2017-07-07