java實現新浪微博Oauth介面發送圖片和文字的方法_java

來源:互聯網
上載者:User

本文執行個體講述了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程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.