推特图片无法正常工作

时间:2014-03-16 07:30:36

标签: c# twitter windows-phone-8 hammock

我尝试使用基于msdn example的代码示例的图片发推文,但它不起作用,任何想法为什么?是推特改变api政策吗?这是我的代码

public void postToTwitter()
{
    try
    {
        var image = new WriteableBitmap(430, 400);
        image.Render(locationPict, null);
        image.Invalidate();
        MemoryStream ms = new MemoryStream();
        image.SaveJpeg(ms, 430, 400, 0, 100);

        const string filename = "/Shared/ShellContent/image.jpg";

        using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
        {
            if (!isf.DirectoryExists("/post"))
            {
                isf.CreateDirectory("/post");
            }
            using (var stream = isf.OpenFile(filename, System.IO.FileMode.OpenOrCreate))
            {
                image.SaveJpeg(stream, 430, 400, 0, 100);
            }
        }

        var credentials = new OAuthCredentials
        {
            Type = OAuthType.ProtectedResource,
            SignatureMethod = OAuthSignatureMethod.HmacSha1,
            ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
            ConsumerKey = twitterAppSettings.consumerKey,
            ConsumerSecret = twitterAppSettings.consumerKeySecret,
            Token = MainUtil.GetKeyValue<string>("twitterAccessToken"),
            TokenSecret = MainUtil.GetKeyValue<string>("twitterAccessTokenSecret"),
            Version = "1.0"
        };

        var restClient = new RestClient
        {
            Authority = "https://api.twitter.com",
            HasElevatedPermissions = true 
        };

        var restRequest = new RestRequest
        {
            Credentials = credentials,
            Path = "1.1/statuses/update_with_media.json",
            Method = WebMethod.Post 
        };

        restRequest.AddField("status", textpost.Text);
        restRequest.AddFile("media[]", image.jpg, ms, "image/jpg");
        restClient.BeginRequest(restRequest, new RestCallback(PostTweetRequestCallback));
    }
    catch(Exception ex)
    {
        string message = "Tweet failed! Exception details: " + ex.ToString();
        MessageBox.Show(message);
    }
}

private void PostTweetRequestCallback(RestRequest request, RestResponse response, object obj)
{
    Deployment.Current.Dispatcher.BeginInvoke(() =>
    {
        if (response.StatusCode == HttpStatusCode.OK)
        {
            MessageBox.Show("TWEET_POSTED_SUCCESSFULLY");
        }
        else if (response.StatusCode == HttpStatusCode.Forbidden)
        {
            MessageBox.Show("TWEET_POST_ERR_UPDATE_LIMIT");
        }
        else
        {
            MessageBox.Show("TWEET_POST_ERR_FAILED");
        }
    });
} 

我在代码中添加了一些调整,以便从msdn示例中的photochooser任务中获取图片,我将其从可保存到Isolatedstorage的writeablebitmap中取出,但我也尝试了类似于msdn并收到错误TWEET_POST_ERR_FAILED

1 个答案:

答案 0 :(得分:0)

尝试向restRequest.AddFile添加字符串&#34; form-data&#34;作为第五个参数:

restRequest.AddFile("media[]", image.jpg, ms, "image/jpg","form-data");