如何在C#中将图像上传到LinkedIn以获得Ugc图像发布

时间:2019-05-20 19:29:40

标签: c# linkedin-api

因此,我遵循Linkedin Documentation来在Linkedin上实施“创建图像共享”。

文档列出了三个步骤:

  1. 注册要上传的图片。
  2. 将您的图片上传到LinkedIn。
  3. 创建图像共享。

虽然我能够执行第一步以获取 uploadUrl ,但是在执行步骤2时却收到了400错误的响应,并带有空白错误消息。

文档将第二步列出为:

curl -i --upload-file /Users/peter/Desktop/superneatimage.png --header "Authorization: Bearer redacted" 'https://api.linkedin.com/mediaUpload/C5522AQGTYER3k3ByHQ/feedshare-uploadedImage/0?ca=vector_feedshare&cn=uploads&m=AQJbrN86Zm265gAAAWemyz2pxPSgONtBiZdchrgG872QltnfYjnMdb2j3A&app=1953784&sync=0&v=beta&ut=2H-IhpbfXrRow1'

这是我在C#代码中的第2步:

private bool UploadImageBinaryFile(RequestUploadUrlResponse uploadDetails)
    {
        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", #access_token#);
            client.DefaultRequestHeaders.Add("X-Restli-Protocol-Version", "2.0.0");
            MultipartFormDataContent form = new MultipartFormDataContent();
            string fileAddress = image_path + "image.png";
            byte[] fileBytes = File.ReadAllBytes(fileAddress);
            string name = "upload-file";
            form.Add(new ByteArrayContent(fileBytes), name);
            HttpResponseMessage response = client.PutAsync
                (
                    uploadDetails.value.uploadMechanism.mediaUploadHttpRequest.uploadUrl,
                    form
            ).Result;

            if (response.IsSuccessStatusCode)//<--getting 400 error Bad Request here
            {
                string responseBody = response.Content.ReadAsStringAsync().Result;
                return true;
            }
            else
            {
                ErrorResponseHandler(response.Content.ReadAsStringAsync().Result);
                return false;
            }
        }
    }

我已确保从第一步开始就能够成功访问uploadUrl。当我使用URL https://api.linkedin.com/v2/assets/ #id#检查状态时,我看到的状态为 WAITING_UPLOAD

我要去哪里错了?

1 个答案:

答案 0 :(得分:0)

我找到了解决方案,基本上我们只需要在内容中传递二进制文件,而我是以形式传递它。

using (HttpClient client = new HttpClient())
{
    try
    {
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accesstoken);
        var content = new ByteArrayContent(File.ReadAllBytes(fileAddress));
        HttpResponseMessage response = client.PutAsync(url, content).Result;
        if (response.IsSuccessStatusCode)
        {
            //response is empty. Have to call the checkAssetStatus to see if the asset is 'AVAILABLE'
            string responseBody = response.Content.ReadAsStringAsync().Result;

        }
        else
        {
            //handleError();
        }
    }
    catch (HttpRequestException ex)
    {
        Console.WriteLine("\nException Caught!");
        Console.WriteLine("Message :{0} ", ex.Message);
    }
}