新浪微博采用Oauth发送图片和文字

基于网上很多人利用新浪api开发新浪微博客户端的时候遇到无法发图片的问题,很多人卡在了这一步。

现将代码呈上,希望能帮到一些朋友。

1 /**
2 * 发表带图片的微博
3 * @param token
4 * @param tokenSecret
5 * @param aFile 要上传的图片文件
6 * @param status 要发表的微博文字
7 * @param urlPath 对应的api地址
8 * @return
9 */
10 public String uploadStatus(String token, String tokenSecret, File aFile, String status, String urlPath) {
11 httpOAuthConsumer = new DefaultOAuthConsumer(consumerKey,consumerSecret);
12 httpOAuthConsumer.setTokenWithSecret(token,tokenSecret);
13 String result = null;
14 try {
15 URL url = new URL(urlPath);
16 HttpURLConnection request = (HttpURLConnection) url.openConnection();
17 request.setDoOutput(true);
18 request.setRequestMethod("POST");
19 HttpParameters para = new HttpParameters();
20 para.put("status", URLEncoder.encode(status,"utf-8").replaceAll("\\+", "%20"));
21 String boundary = "---------------------------37531613912423";
22 String content = "--"+boundary+"\r\nContent-Disposition: form-data; name=\"status\"\r\n\r\n";
23 String pic = "\r\n--"+boundary+"\r\nContent-Disposition: form-data; name=\"pic\"; filename=\"image.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n";
24 byte[] end_data = ("\r\n--" + boundary + "--\r\n").getBytes();
25 FileInputStream stream = new FileInputStream(aFile);
26 byte[] file = new byte[(int) aFile.length()];
27 stream.read(file);
28 request.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary); //设置表单类型和分隔符
29 request.setRequestProperty("Content-Length", String.valueOf(content.getBytes().length + status.getBytes().length + pic.getBytes().length + aFile.length() + end_data.length)); //设置内容长度 
          //下面的步骤是对请求进行签名。
30 httpOAuthConsumer.setAdditionalParameters(para);
31 httpOAuthConsumer.sign(request);
32 OutputStream ot = request.getOutputStream();
33 ot.write(content.getBytes());
34 ot.write(status.getBytes());
35 ot.write(pic.getBytes());
36 ot.write(file);
37 ot.write(end_data);
38 ot.flush();
39 ot.close();
40 request.connect();
41 if (200 == request.getResponseCode()) {
42 result = "SUCCESS";
43 }
44 } catch (FileNotFoundException e1) {
45 e1.printStackTrace();
46 } catch (IOException e) {
47 e.printStackTrace();
48 } catch (OAuthMessageSignerException e) {
49 e.printStackTrace();
50 } catch (OAuthExpectationFailedException e) {
51 e.printStackTrace();
52 } catch (OAuthCommunicationException e) {
53 e.printStackTrace();
54 }
55 return result;
56 }

posted on 2011-07-06 09:45  细节决定成败  阅读(406)  评论(0)    收藏  举报

导航