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代码 复制代码  收藏代码
  1. /*  
  2.  * 新浪微博发送图片post方法,自己构造相应的请求内容  
  3.  */  
  4.     public String uploadStatus(File aFile, String status, String urlPath)   
  5.             throws OAuthMessageSignerException,   
  6.             OAuthExpectationFailedException, OAuthCommunicationException,   
  7.             IOException {   
  8.         OAuthConsumer httpOAuthConsumer = new DefaultOAuthConsumer(   
  9.                 consumer.getConsumerKey(), consumer.getConsumerSecret());   
  10.         httpOAuthConsumer.setTokenWithSecret(consumer.getToken(),   
  11.                 consumer.getTokenSecret());   
  12.         String result = null;   
  13.   
  14.         URL url = new URL(urlPath);   
  15.         HttpURLConnection request = (HttpURLConnection) url.openConnection();   
  16.         request.setDoOutput(true);   
  17.         request.setDoInput(true);   
  18.         request.setRequestMethod("POST");   
  19.         HttpParameters para = new HttpParameters();   
  20.         para.put("status",   
  21.                 URLEncoder.encode(status, "utf-8").replaceAll("\\+""%20"));   
  22.         // para.put("source",URLEncoder.encode(status,   
  23.         // "utf-8").replaceAll("\\+", "%20"));   
  24.         String boundary = "---------------------------37531613912423";   
  25.         String content = "--" + boundary   
  26.                 + "\r\nContent-Disposition: form-data; name=\"status\"\r\n\r\n";   
  27.         String pic = "\r\n--"  
  28.                 + boundary   
  29.                 + "\r\nContent-Disposition: form-data; name=\"pic\"; filename=\"image.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n";   
  30.         byte[] end_data = ("\r\n--" + boundary + "--\r\n").getBytes();   
  31.         FileInputStream stream = new FileInputStream(aFile);   
  32.         byte[] file = new byte[(int) aFile.length()];   
  33.         stream.read(file);   
  34.         request.setRequestProperty("Content-Type",   
  35.                 "multipart/form-data; boundary=" + boundary); // 设置表单类型和分隔符   
  36.         request.setRequestProperty(   
  37.                 "Content-Length",   
  38.                 String.valueOf(content.getBytes().length   
  39.                         + status.getBytes().length + pic.getBytes().length   
  40.                         + aFile.length() + end_data.length)); // 设置内容长度   
  41.                                                                 //             
  42.         // 下面的步骤是对请求进行签名。   
  43.         httpOAuthConsumer.setAdditionalParameters(para);   
  44.         httpOAuthConsumer.sign(request);   
  45.         //讲相应的请求参数写入到entity中   
  46.         OutputStream ot = request.getOutputStream();   
  47.         ot.write(content.getBytes());   
  48.         ot.write(status.getBytes());   
  49.         ot.write(pic.getBytes());   
  50.         ot.write(file);   
  51.         ot.write(end_data);   
  52.         ot.flush();   
  53.         ot.close();   
  54.         request.connect();   
  55.         InputStream is = request.getInputStream();   
  56.         BufferedReader reader = new BufferedReader(new InputStreamReader(is));   
  57.         String line = null;   
  58.         StringBuffer sb = new StringBuffer();   
  59.         while ((line = reader.readLine()) != null) {   
  60.             sb.append(line);   
  61.         }   
  62.         result = sb.toString();   
  63.         System.out.println("reuslt---->" + result);   
  64.         System.out.println(request.getResponseMessage());   
  65.         /*  
  66.          * if (200 == request.getResponseCode()) { result = "SUCCESS"; }  
  67.          */  
  68.   
  69.         return result;   
  70.     }  
/*
 * 新浪微博发送图片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代码 复制代码  收藏代码
  1. /*  
  2.  * 新浪微博发送图片post方法  
  3.  */  
  4.     public String doPostWithMultipart(String url,List<NameValuePair> pairs,String pic) throws IllegalCharsetNameException, UnsupportedCharsetException, ClientProtocolException, IOException, OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException{   
  5.         HttpPost postRequest = new HttpPost(url);   
  6.         MultipartEntity reqEntity = new MultipartEntity();   
  7.         for(NameValuePair p:pairs){   
  8.             reqEntity.addPart(p.getName(),new StringBody(p.getValue(),Charset.forName("UTF-8")));   
  9.         }   
  10.         FileBody filebody = new FileBody(new File(pic),"image/jpeg");   
  11.         reqEntity.addPart("pic",filebody);   
  12.         postRequest.setEntity(reqEntity);   
  13.         consumer.sign(postRequest);   
  14.         HttpClient httpclient = new DefaultHttpClient();   
  15.         HttpResponse response = null;   
  16.         response = httpclient.execute(postRequest);   
  17.         String result = ApacheUtils.getResponseText(response);   
  18.         return result;   
  19.            
  20.     }  
/*
 * 新浪微博发送图片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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值