Jab*_*ari 0 twitter android oauth scribe
我目前正在使用Scribe成功验证并向Twitter发布非媒体消息.这很容易,我发布的第一条测试消息没有任何问题.但是,我似乎根本无法发布照片.我已经回顾了Twitter在这里和这里发布媒体的说明.
Github上的所有Scribe/Twitter示例都是针对非媒体帖子的.如果有人能提供一个如何通过Scribe将照片发布到Twitter的可靠示例,那就太棒了!
我特别有两个问题:
1)我的帖子不会通过授权.我试过模仿上面发布的例子,但似乎没什么用.
2)当将图像从byte []转换为字符串时,我似乎只能在它停止之前获得4113个字符.根据我的理解,这远远低于String可以容纳的字符数.
这是我如何提取照片:
// GET PHOTO FILE AND FILE LENGTH
// INSTANTIATE UPLOAD VARIABLE WITH FILE LENGTH
File file = new File(photo); // ("photo" is a string path to the photo file)
int fileLength = (int) file.length();
uploadFile = new byte[fileLength];
// CREATE BUFFER INPUT STREAM OF FILE
BufferedInputStream inputStream;
try {inputStream = new BufferedInputStream(new FileInputStream(file));}
catch (FileNotFoundException e)
{
inputStream = null;
Toast.makeText(this.getApplicationContext(), "Buffer input stream error!", Toast.LENGTH_LONG).show();
}
// READ DATA FROM FILE INTO UPLOAD VARIABLE
// CLOSE INPUT STREAM
try {inputStream.read(uploadFile);}
catch (IOException e) {Toast.makeText(this.getApplicationContext(), "Read input stream to upload variable error!", Toast.LENGTH_LONG).show();}
try {inputStream.close();}
catch (IOException e) {Toast.makeText(this.getApplicationContext(), "Close input stream error!", Toast.LENGTH_LONG).show();}
Run Code Online (Sandbox Code Playgroud)
经过大量研究和来自不同地方的铣削代码后,我终于弄清楚我做错了什么.以下是如何通过Scribe OAuth将照片发布到Twitter的示例:
注意:这假设了一些事情......
1)您已经保存了照片并拥有文件路径
2)您已经在某个时刻对用户进行了身份验证,并拥有有效的访问令牌
3)您必须将apache-mime4j-0.6.jar和httpmime-4.0.1.jar添加到您的libs文件夹并将它们包含在您的构建路径中!
我真的希望这有助于某人!它很容易实现,但需要几天的故障排除才能使其正常工作!
// BUILD OAUTH SERVICE
OAuthService oAuth = new ServiceBuilder()
.provider(TwitterApi.class)
.apiKey(YOUR_TWITTER_API_KEY) // REPLACE WITH YOUR OWN!!!
.apiSecret(YOUR_TWITTER_API_SECRET) // REPLACE WITH YOUR OWN!!!
.callback(YOUR_CALLBACK) // REPLACE WITH YOUR OWN!!!
.build();
// BUILD OAUTH REQUEST & SIGN IT RIGHT AWAY (OTHERWISE MULTIPART FORM MAY PREVENT SIGNING)
OAuthRequest request = new OAuthRequest(Verb.POST, "https://upload.twitter.com/1.1/statuses/update_with_media.json");
oAuth.signRequest(USER_ACCESS_TOKEN, request); // ENTER USER'S ACCESS TOKEN
// ADD MULTIPART FORM
try
{
MultipartEntity entity = new MultipartEntity();
entity.addPart("status", new StringBody(message)); // THIS IS THE TWITTER MESSAGE
entity.addPart("media", new FileBody(new File(photo))); // THIS IS THE PHOTO TO UPLOAD
ByteArrayOutputStream out = new ByteArrayOutputStream();
entity.writeTo(out);
request.addPayload(out.toByteArray());
request.addHeader(entity.getContentType().getName(), entity.getContentType().getValue());
}
catch (UnsupportedEncodingException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
// SEND REQUEST
try {response = new JSONObject (request.send().getBody());}
catch (JSONException e) {Log.e("YOUR_APP_TAG", "JSONException Thrown: " + e.getMessage());}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1303 次 |
| 最近记录: |