天天看點

Android:SNS用戶端開發八:發送帶圖檔的微網誌(二)(發送多媒體的post方法)

      好了,之前我們已經擷取到了需要發送的圖檔存在于手機中的路徑,也就是上一篇文章中的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代碼

Android:SNS用戶端開發八:發送帶圖檔的微網誌(二)(發送多媒體的post方法)
Android:SNS用戶端開發八:發送帶圖檔的微網誌(二)(發送多媒體的post方法)
Android:SNS用戶端開發八:發送帶圖檔的微網誌(二)(發送多媒體的post方法)
  1.     public String uploadStatus(File aFile, String status, String urlPath)   
  2.             throws OAuthMessageSignerException,   
  3.             OAuthExpectationFailedException, OAuthCommunicationException,   
  4.             IOException {   
  5.         OAuthConsumer httpOAuthConsumer = new DefaultOAuthConsumer(   
  6.                 consumer.getConsumerKey(), consumer.getConsumerSecret());   
  7.         httpOAuthConsumer.setTokenWithSecret(consumer.getToken(),   
  8.                 consumer.getTokenSecret());   
  9.         String result = null;   
  10.         URL url = new URL(urlPath);   
  11.         HttpURLConnection request = (HttpURLConnection) url.openConnection();   
  12.         request.setDoOutput(true);   
  13.         request.setDoInput(true);   
  14.         request.setRequestMethod("POST");   
  15.         HttpParameters para = new HttpParameters();   
  16.         para.put("status",   
  17.                 URLEncoder.encode(status, "utf-8").replaceAll("\\+", "%20"));   
  18.         // para.put("source",URLEncoder.encode(status,   
  19.         // "utf-8").replaceAll("\\+", "%20"));   
  20.         String boundary = "---------------------------37531613912423";   
  21.         String content = "--" + boundary   
  22.                 + "\r\nContent-Disposition: form-data; name=\"status\"\r\n\r\n";   
  23.         String pic = "\r\n--"  
  24.                 + boundary   
  25.                 + "\r\nContent-Disposition: form-data; name=\"pic\"; filename=\"image.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n";   
  26.         byte[] end_data = ("\r\n--" + boundary + "--\r\n").getBytes();   
  27.         FileInputStream stream = new FileInputStream(aFile);   
  28.         byte[] file = new byte[(int) aFile.length()];   
  29.         stream.read(file);   
  30.         request.setRequestProperty("Content-Type",   
  31.                 "multipart/form-data; boundary=" + boundary); // 設定表單類型和分隔符   
  32.         request.setRequestProperty(   
  33.                 "Content-Length",   
  34.                 String.valueOf(content.getBytes().length   
  35.                         + status.getBytes().length + pic.getBytes().length   
  36.                         + aFile.length() + end_data.length)); // 設定内容長度   
  37.                                                                 //             
  38.         // 下面的步驟是對請求進行簽名。   
  39.         httpOAuthConsumer.setAdditionalParameters(para);   
  40.         httpOAuthConsumer.sign(request);   
  41.         //講相應的請求參數寫入到entity中   
  42.         OutputStream ot = request.getOutputStream();   
  43.         ot.write(content.getBytes());   
  44.         ot.write(status.getBytes());   
  45.         ot.write(pic.getBytes());   
  46.         ot.write(file);   
  47.         ot.write(end_data);   
  48.         ot.flush();   
  49.         ot.close();   
  50.         request.connect();   
  51.         InputStream is = request.getInputStream();   
  52.         BufferedReader reader = new BufferedReader(new InputStreamReader(is));   
  53.         String line = null;   
  54.         StringBuffer sb = new StringBuffer();   
  55.         while ((line = reader.readLine()) != null) {   
  56.             sb.append(line);   
  57.         }   
  58.         result = sb.toString();   
  59.         System.out.println("reuslt---->" + result);   
  60.         System.out.println(request.getResponseMessage());   
  61.         return result;   
  62.     }  
/*
 * 新浪微網誌發送圖檔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代碼

Android:SNS用戶端開發八:發送帶圖檔的微網誌(二)(發送多媒體的post方法)
Android:SNS用戶端開發八:發送帶圖檔的微網誌(二)(發送多媒體的post方法)
Android:SNS用戶端開發八:發送帶圖檔的微網誌(二)(發送多媒體的post方法)
  1.     public String doPostWithMultipart(String url,List<NameValuePair> pairs,String pic) throws IllegalCharsetNameException, UnsupportedCharsetException, ClientProtocolException, IOException, OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException{   
  2.         HttpPost postRequest = new HttpPost(url);   
  3.         MultipartEntity reqEntity = new MultipartEntity();   
  4.         for(NameValuePair p:pairs){   
  5.             reqEntity.addPart(p.getName(),new StringBody(p.getValue(),Charset.forName("UTF-8")));   
  6.         }   
  7.         FileBody filebody = new FileBody(new File(pic),"image/jpeg");   
  8.         reqEntity.addPart("pic",filebody);   
  9.         postRequest.setEntity(reqEntity);   
  10.         consumer.sign(postRequest);   
  11.         HttpClient httpclient = new DefaultHttpClient();   
  12.         HttpResponse response = null;   
  13.         response = httpclient.execute(postRequest);   
  14.         String result = ApacheUtils.getResponseText(response);   
  15.         return result;   
  16.     }  
/*
 * 新浪微網誌發送圖檔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