本文實例講述了java實現(xiàn)新浪微博Oauth接口發(fā)送圖片和文字的方法。分享給大家供大家參考。具體如下:
基于網(wǎng)上很多人利用新浪api開發(fā)新浪微博客戶端的時候遇到無法發(fā)圖片的問題,很多人卡在了這一布。現(xiàn)將代碼呈上,希望能幫到一些朋友。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
/** * 發(fā)表帶圖片的微博 * @param token * @param tokenSecret * @param aFile * @param status * @param urlPath * @return */ public String uploadStatus(String token, String tokenSecret, File aFile, String status, String urlPath) { httpOAuthConsumer = new DefaultOAuthConsumer(consumerKey,consumerSecret); httpOAuthConsumer.setTokenWithSecret(token,tokenSecret); String result = null ; try { URL url = new URL(urlPath); HttpURLConnection request = (HttpURLConnection) url.openConnection(); request.setDoOutput( true ); request.setRequestMethod( "POST" ); HttpParameters para = new HttpParameters(); para.put( "status" , 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); //設(shè)置表單類型和分隔符 request.setRequestProperty( "Content-Length" , String.valueOf(content.getBytes().length + status.getBytes().length + pic.getBytes().length + aFile.length() + end_data.length)); //設(shè)置內(nèi)容長度 httpOAuthConsumer.setAdditionalParameters(para); httpOAuthConsumer.sign(request); 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(); if ( 200 == request.getResponseCode()) { result = "SUCCESS" ; } } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (OAuthMessageSignerException e) { e.printStackTrace(); } catch (OAuthExpectationFailedException e) { e.printStackTrace(); } catch (OAuthCommunicationException e) { e.printStackTrace(); } return result; } |
希望本文所述對大家的java程序設(shè)計有所幫助。