好了,之前我們已經擷取到了需要發送的圖檔存在于手機中的路徑,也就是上一篇文章中的picPath,那麼我們今天通過這個路徑将圖檔發出去。
先看新浪微網誌對發送圖檔的說明:http://open.weibo.com/wiki/Statuses/upload。在注意事項中新浪寫到:上傳圖檔需要采用multipart/form-data方式送出pic參數,并且放在POST請求的body裡。另外,隻有以oauth_開頭的參數才需要參加OAuth的簽名。
我們可以采取兩種方法來實作這樣的一個post方法,1、通過HttpURLConnectiion自己構造一個http請求的全部内容2、同樣是通過HttpClient開源項目,但是我們需要添加一個額外的包,包名為:httpmine-4.X,大家可以自行下載下傳。
首先給出第一種方法,此處參考http://www.itivy.com/android/archive/2011/7/6/android-weibo-oauth-send-text-and-image.html給出的方法實作,特别感謝。
Java代碼

- public String uploadStatus(File aFile, String status, String urlPath)
- throws OAuthMessageSignerException,
- OAuthExpectationFailedException, OAuthCommunicationException,
- IOException {
- OAuthConsumer httpOAuthConsumer = new DefaultOAuthConsumer(
- consumer.getConsumerKey(), consumer.getConsumerSecret());
- httpOAuthConsumer.setTokenWithSecret(consumer.getToken(),
- consumer.getTokenSecret());
- String result = null;
- URL url = new URL(urlPath);
- HttpURLConnection request = (HttpURLConnection) url.openConnection();
- request.setDoOutput(true);
- request.setDoInput(true);
- request.setRequestMethod("POST");
- HttpParameters para = new HttpParameters();
- para.put("status",
- URLEncoder.encode(status, "utf-8").replaceAll("\\+", "%20"));
- // para.put("source",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);
- //講相應的請求參數寫入到entity中
- 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();
- InputStream is = request.getInputStream();
- BufferedReader reader = new BufferedReader(new InputStreamReader(is));
- String line = null;
- StringBuffer sb = new StringBuffer();
- while ((line = reader.readLine()) != null) {
- sb.append(line);
- }
- result = sb.toString();
- System.out.println("reuslt---->" + result);
- System.out.println(request.getResponseMessage());
- return result;
- }
/*
* 新浪微網誌發送圖檔post方法,自己構造相應的請求内容
*/
public String uploadStatus(File aFile, String status, String urlPath)
throws OAuthMessageSignerException,
OAuthExpectationFailedException, OAuthCommunicationException,
IOException {
OAuthConsumer httpOAuthConsumer = new DefaultOAuthConsumer(
consumer.getConsumerKey(), consumer.getConsumerSecret());
httpOAuthConsumer.setTokenWithSecret(consumer.getToken(),
consumer.getTokenSecret());
String result = null;
URL url = new URL(urlPath);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.setDoOutput(true);
request.setDoInput(true);
request.setRequestMethod("POST");
HttpParameters para = new HttpParameters();
para.put("status",
URLEncoder.encode(status, "utf-8").replaceAll("\\+", "%20"));
// para.put("source",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);
//講相應的請求參數寫入到entity中
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();
InputStream is = request.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = null;
StringBuffer sb = new StringBuffer();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
result = sb.toString();
System.out.println("reuslt---->" + result);
System.out.println(request.getResponseMessage());
/*
* if (200 == request.getResponseCode()) { result = "SUCCESS"; }
*/
return result;
}
構造原理,在新浪微網誌注意事項中已經寫的十厘清楚,此處就不再做過多的解釋。這裡尤其值得注意的是:寫入的占位符\r\n等均不可缺少,不然無法構造正确的請求内容。
第二種方法:
Java代碼

- public String doPostWithMultipart(String url,List<NameValuePair> pairs,String pic) throws IllegalCharsetNameException, UnsupportedCharsetException, ClientProtocolException, IOException, OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException{
- HttpPost postRequest = new HttpPost(url);
- MultipartEntity reqEntity = new MultipartEntity();
- for(NameValuePair p:pairs){
- reqEntity.addPart(p.getName(),new StringBody(p.getValue(),Charset.forName("UTF-8")));
- }
- FileBody filebody = new FileBody(new File(pic),"image/jpeg");
- reqEntity.addPart("pic",filebody);
- postRequest.setEntity(reqEntity);
- consumer.sign(postRequest);
- HttpClient httpclient = new DefaultHttpClient();
- HttpResponse response = null;
- response = httpclient.execute(postRequest);
- String result = ApacheUtils.getResponseText(response);
- return result;
- }
/*
* 新浪微網誌發送圖檔post方法
*/
public String doPostWithMultipart(String url,List<NameValuePair> pairs,String pic) throws IllegalCharsetNameException, UnsupportedCharsetException, ClientProtocolException, IOException, OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException{
HttpPost postRequest = new HttpPost(url);
MultipartEntity reqEntity = new MultipartEntity();
for(NameValuePair p:pairs){
reqEntity.addPart(p.getName(),new StringBody(p.getValue(),Charset.forName("UTF-8")));
}
FileBody filebody = new FileBody(new File(pic),"image/jpeg");
reqEntity.addPart("pic",filebody);
postRequest.setEntity(reqEntity);
consumer.sign(postRequest);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = null;
response = httpclient.execute(postRequest);
String result = ApacheUtils.getResponseText(response);
return result;
}
兩種方法均可使用
轉自:http://river418.iteye.com/blog/1297497