本以為新浪發布圖片和發布文字一樣的簡單,但很悲劇。。。。。。。遠不是想象的那樣。
現在分享一下代碼。
/**<br /> * 發錶帶圖片的微博<br /> *<br /> * @param token<br /> * @param tokenSecret<br /> * @param status<br /> * 發表的內容<br /> * @param urlPath<br /> * 圖片的地址 本函數沒有用到,我直接在函數中建立的。<br /> * @return<br /> */<br />public static void uploadStatus(String token, String tokenSecret, String imageUrl, String status)<br />{<br />File files = Environment.getExternalStorageDirectory();<br />String sdPath = files.getAbsolutePath();<br />// 請保證SD卡根目錄下有這張圖片檔案<br />String urlPath = sdPath + "/" + "c.jpg";<br />File imageFile = new File(urlPath);<br />if (!imageFile.exists())<br />{<br />System.out.println("沒有該圖片");<br />}<br />httpOauthConsumer = new DefaultOAuthConsumer("你的AppKey","你的AppSecret");//記得用你的替換一下<br />httpOauthConsumer.setTokenWithSecret(token, tokenSecret);//token tokenSecret之前工作的任務<br />try<br />{<br />URL url = new URL(Constants.XinLangUpload);//URL:http://api.t.sina.com.cn/statuses/upload.json<br />HttpURLConnection request = (HttpURLConnection) url.openConnection();<br />request.setDoOutput(true);<br />request.setRequestMethod("POST");<br />HttpParameters httpParameters = new HttpParameters();<br />httpParameters.put("status", URLEncoder.encode(status, "utf-8").replaceAll("\\+", "%20"));<br />String boundary = "---------------------------37531613912423";<br />String content = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"status\"\r\n\r\n";<br />String pic = "\r\n--"<br />+ boundary<br />+ "\r\nContent-Disposition: form-data; name=\"pic\"; filename=\"image.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n";<br />byte[] end_data = ("\r\n--" + boundary + "--\r\n").getBytes();<br />FileInputStream stream = new FileInputStream(imageFile);<br />byte[] file = new byte[(int) imageFile.length()];<br />stream.read(file);<br />request.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); // 設定表單類型和分隔字元<br />request.setRequestProperty(<br />"Content-Length",<br />String.valueOf(content.getBytes().length + status.getBytes().length + pic.getBytes().length<br />+ imageFile.length() + end_data.length)); // 設定內容長度<br />httpOauthConsumer.setAdditionalParameters(httpParameters);<br />httpOauthConsumer.sign(request);<br />OutputStream outputStream = request.getOutputStream();<br />outputStream.write(content.getBytes());<br />outputStream.write(status.getBytes());<br />outputStream.write(pic.getBytes());<br />outputStream.write(file);<br />outputStream.write(end_data);<br />outputStream.flush();<br />outputStream.close();<br />request.connect();<br />if (200 == request.getResponseCode())<br />{<br />System.out.println("發布成功");<br />}<br />else<br />{<br />System.out.println("異常code:" + request.getResponseCode());<br />}<br />}<br />catch (Exception e1)<br />{<br />e1.printStackTrace();<br />}<br />}