因此,我正在开发一个小应用程序,该应用程序当前将指定图像从硬盘发布到 Google 的反向图像搜索并处理响应。问题是我得到的响应不是预期的。我已经尽我所能复制 POST 请求的结构,但我终其一生都无法弄清楚为什么我没有得到预期的响应。我确实收到了 200 响应代码,但 HTML 输出是某种 Google 错误(按图片搜索不可用。请在几个小时后重试)。我已经使用 Fiddler 来确定请求的结构,据我所知,从我的应用程序生成的请求几乎是相同的,除了缺少 Cookie 标头(可能是这样吗?)。如果是这样,我将如何创建一个 cookie 并将其插入我的请求中?
这是我的代码:(注意:我确信它可以写得更有说服力和效率(例如使用 StringBuilder),我已经硬编码了很多,但它应该足以暂时测试基本功能)
String^ url = "https://www.google.com/searchbyimage/upload";
HttpWebRequest^ request = (HttpWebRequest^) WebRequest::Create(url);
request->Method = "POST";
request->UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko/20100101 Firefox/16.0";
request->Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request->Headers["Accept-Language"] = "en-US,en;q=0.5";
request->Headers["Accept-Encoding"] = "gzip, deflate";
String^ boundary = "-----------------------------23281168279961";
request->ContentType = "multipart/form-data; boundary=" + boundary;
request->Referer = "https://www.google.com/imghp?hl=en&tab=wi";
String^ header = boundary + "\n";
header += "Content-Disposition: form-data; name=\"image_url\"\n\n\n";
header += boundary + "\n";
header += "Content-Disposition: form-data; name=\"encoded_image\"; filename=\"2010-04-09-ec52529.png\"\n";
header += "Content-Type: image/png\n\n";
String^ footer = "\n" + boundary + "\n";
footer += "Content-Disposition: form-data; name=\"image_content\"\n\n\n";
footer += boundary + "\n";
footer += "Content-Disposition: form-data; name=\"filename\"\n\n\n";
footer += boundary + "\n";
footer += "Content-Disposition: form-data; name=\"num\"\n\n";
footer += "10\n";
footer += boundary + "\n";
footer += "Content-Disposition: form-data; name=\"hl\"\n\n";
footer += "en\n";
footer += boundary + "\n";
footer += "Content-Disposition: form-data; name=\"safe\"\n\n";
footer += "off\n";
footer += boundary + "\n";
footer += "Content-Disposition: form-data; name=\"bih\"\n\n";
footer += "578\n";
footer += boundary + "\n";
footer += "Content-Disposition: form-data; name=\"biw\"\n\n";
footer += "1366\n";
footer += boundary + "--\n";
array<Byte>^ headerData = Encoding::ASCII->GetBytes(header);
array<Byte>^ imageData = File::ReadAllBytes(oldImage);
array<Byte>^ footerData = Encoding::ASCII->GetBytes(footer);
request->ContentLength = headerData->Length + imageData->Length + footerData->Length;
Stream^ reqStream = request->GetRequestStream();
reqStream->Write(headerData, 0, headerData->Length);
reqStream->Write(imageData, 0, imageData->Length);
reqStream->Write(footerData, 0, footerData->Length);
HttpWebResponse^ response = (HttpWebResponse^) request->GetResponse();
StreamReader^ reader = gcnew StreamReader(response->GetResponseStream());
String^ things = reader->ReadToEnd();