好了,之前我们已经获取到了需要发送的图片存在于手机中的路径,也就是上一篇文章中的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