我的问题与这篇文章有关:Etsy API Image upload error but from a C# point of view。
其他一切正常,例如,我能够对 Etsy 进行经过身份验证的调用以创建列表,但现在我在尝试将图像附加到 Etsy 列表时开始收到错误“请求正文太大”。该请求曾经像我有一个示例响应一样工作,但现在它简单地失败了。
我通常做的是使用来自 Etsy 的密钥和令牌设置一个 Rest Client。然后我设置了一个 Rest Request 并将其传递给 Rest Client 的 Execute 方法,即:
...
// Set up the rest client...
RestClient restClient = new RestClient();
restClient.BaseUrl = new System.Uri("https://openapi.etsy.com/v2/");
restClient.Authenticator = RestSharp.Authenticators.OAuth1Authenticator.ForProtectedResource(ConsumerKey, ConsumerSecret, PermanentAccessTokenKey, PermanentAccessTokenSecret);
// Set up the request...
RestRequest request = new RestRequest();
request.Resource = "An Etsy end point";
request.Method = Method.POST;
...
IRestResponse response = restClient.Execute(request);
...
我正在使用 RestSharp 来处理 OAuthentication。
主要的兴趣在于:
...
request.AddHeader("Content-Type", "multipart/form-data");
request.AlwaysMultipartFormData = true;
request.AddParameter("image", localImageFilenames[i]);
request.AddParameter("type", "image/" + imageType);
request.AddParameter("rank", imageRank++);
request.AddFile("image", imageByteArray, localImageFilenames[i], "image/" + imageType);
request.Resource = "/listings/{0}/images".Replace("{0}", etsyListingId.ToString()); // eg "/listings/559242925/images";
request.Method = Method.POST;
response = restClient.Execute(request);
...
响应在哪里:
"StatusCode: BadRequest, Content-Type: text/plain;charset=UTF-8, Content-Length: 29)"
Content: "The request body is too large"
ContentEncoding: ""
ContentLength: 29
ContentType: "text/plain;charset=UTF-8"
Cookies: Count = 3
ErrorException: null
ErrorMessage: null
Headers: Count = 9
IsSuccessful: false
ProtocolVersion: {1.1}
RawBytes: {byte[29]}
Request: {RestSharp.RestRequest}
ResponseStatus: Completed
ResponseUri: {https://openapi.etsy.com/v2/listings/605119036/images}
Server: "Apache"
StatusCode: BadRequest
StatusDescription: "Bad Request"
content: "The request body is too large"
然后是一个连接休息客户端的主程序:
/// <summary>
/// Upload and attach the list of images to the specified Etsy listing id.
/// </summary>
/// <param name="restClient">Connected Etsy client</param>
/// <param name="localImageFilenames">List of local images to attach to the listing (ordered in rank order).</param>
/// <param name="etsyListingId">The Etsy listing's listing id to which images will be attached.</param>
public void AttachImagesToProduct(RestClient restClient, List<string> imageFilenames, int etsyListingId, string localTemporaryDirectory)
{
int imageRank = 1;
string localImageFilename = null;
List<string> localImageFilenames = new List<string>();
// Before we reattach images, Etsy only caters for local image filesname eg ones that reside on the user's PC (and not http://...).
// So, if the images beign with http... then we need to download them locally, upload them and then delete...
for (int i = 0; i < imageFilenames.Count; i++)
{
if (imageFilenames[i].ToLower().Trim().StartsWith("http"))
{
// Download...
localImageFilename = Orcus.CommonLibrary.Images.DownloadRemoteImageFile(imageFilenames[i], localTemporaryDirectory);
}
else
{
localImageFilename = imageFilenames[i];
}
if (!string.IsNullOrEmpty(localImageFilename))
{
localImageFilenames.Add(localImageFilename);
}
}
for (int i = 0; i < localImageFilenames.Count; i++)
{
try
{
if (File.Exists(localImageFilenames[i]) && etsyListingId > 0)
{
// https://stackoverflow.com/questions/7413184/converting-a-jpeg-image-to-a-byte-array-com-exception
// https://blog.tyrsius.com/restsharp-file-upload/
// https://nediml.wordpress.com/2012/05/10/uploading-files-to-remote-server-with-multiple-parameters/
// And also sample code from https://github.com/ChrisGraham84/EtsyAPIConsumer
using (MemoryStream ms = new MemoryStream())
{
Image img = Image.FromFile(localImageFilenames[i]);
string imageType = DetermineImageType(img);
System.Drawing.Imaging.ImageFormat imageFormat = DetermineImageFormat(img);
byte[] imageByteArray;
RestRequest request = new RestRequest();
IRestResponse response;
img.Save(ms, imageFormat);
imageByteArray = ms.ToArray();
request.AddHeader("Content-Type", "multipart/form-data");
request.AlwaysMultipartFormData = true;
request.AddParameter("image", localImageFilenames[i]);
request.AddParameter("type", "image/" + imageType);
request.AddParameter("rank", imageRank++);
request.AddFile("image", imageByteArray, localImageFilenames[i], "image/" + imageType);
request.AddJsonBody(null);
request.Resource = "/listings/{0}/images".Replace("{0}", etsyListingId.ToString()); // eg "/listings/559242925/images";
request.Method = Method.POST;
response = restClient.Execute(request);
}
}
}
catch (Exception ex)
{
// Image n failed to up attached so skip it...
}
} // for...
}
/// <summary>
/// Determine the image type.
/// </summary>
/// <param name="localImage">The local image to be eventually uploaded to Etsy.</param>
/// <returns>The image's type. Default is Jpeg.</returns>
private string DetermineImageType(Image localImage)
{
string imageType = "jpeg";
if (System.Drawing.Imaging.ImageFormat.Jpeg.Equals(localImage.RawFormat))
{
imageType = "jpeg";
}
else if (System.Drawing.Imaging.ImageFormat.Gif.Equals(localImage.RawFormat))
{
imageType = "gif";
}
else if (System.Drawing.Imaging.ImageFormat.Bmp.Equals(localImage.RawFormat))
{
imageType = "bmp";
}
else if (System.Drawing.Imaging.ImageFormat.Png.Equals(localImage.RawFormat))
{
imageType = "png";
}
else if (System.Drawing.Imaging.ImageFormat.Tiff.Equals(localImage.RawFormat))
{
imageType = "tiff";
}
return imageType;
}
/// <summary>
/// Determines the image's image format.
/// </summary>
/// <param name="localImage">The local image to be eventually uploaded to Etsy</param>
/// <returns>The image's format. Default is Jpeg.</returns>
private System.Drawing.Imaging.ImageFormat DetermineImageFormat(Image localImage)
{
System.Drawing.Imaging.ImageFormat imgFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
if (System.Drawing.Imaging.ImageFormat.Jpeg.Equals(localImage.RawFormat))
{
imgFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
}
else if (System.Drawing.Imaging.ImageFormat.Gif.Equals(localImage.RawFormat))
{
imgFormat = System.Drawing.Imaging.ImageFormat.Gif;
}
else if (System.Drawing.Imaging.ImageFormat.Bmp.Equals(localImage.RawFormat))
{
imgFormat = System.Drawing.Imaging.ImageFormat.Bmp;
}
else if (System.Drawing.Imaging.ImageFormat.Png.Equals(localImage.RawFormat))
{
imgFormat = System.Drawing.Imaging.ImageFormat.Png;
}
else if (System.Drawing.Imaging.ImageFormat.Tiff.Equals(localImage.RawFormat))
{
imgFormat = System.Drawing.Imaging.ImageFormat.Tiff;
}
return imgFormat;
}
这不是文件大小问题,因为我尝试过使用 20K 图像文件。
我认为问题与我没有在请求中设置一些边界有关?我见过的所有“解决方案”都没有使用 OAuthentication 和 RestSharp。
Brian Grinstead 的文章https://briangrinstead.com/blog/multipart-form-post-in-c/似乎很有希望,但我不明白如何将已设置的 Rest Client 与 Etsy 密钥集成以进行经过身份验证的调用.
[编辑]
指针将非常受欢迎。