天天看点

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