Httpwebrequest上传文字和图片

时间:2017-10-14 15:40:01

标签: c# httpwebrequest webrequest

我想使用HttpWebRequest在olx.ba上发布广告。要发布广告,我必须先登录,因此我从该请求中获取了Cookie并将其传递给发布广告的请求。到目前为止,广告已正确发布,但广告中没有图片。

public void PostProduct(Account account, Product product)
    {
        // Get login cookies
        CookieCollection cookieCollection = GetLoginCookies(account);

        request = InitializeRequest(request, "https://www.olx.ba/objava/zavrsi");

        // Set the login cookies
        foreach (Cookie c in response.Cookies)
        {
            request.CookieContainer.Add(c);
        }

        postData = Encoding.ASCII.GetBytes(UrlHelpers.ToQueryString(product));
        request.ContentLength = postData.Length;

        using (var stream = request.GetRequestStream())
        {
            stream.Write(postData, 0, postData.Length);
        }

        response = (HttpWebResponse)request.GetResponse();

        // responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
    }

该网站有一个上传图片的表格,当我选择要上传的图片时,这是该表格的要求:

请求标题

POST /objava/upload?s=RBDQpWEcUu HTTP/1.1
Host: www.olx.ba
Connection: keep-alive
Content-Length: 283041
Pragma: no-cache
Cache-Control: no-cache
Origin: https://www.olx.ba
X-File-Name: 2.jpg
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36
Content-Type: multipart/form-data; boundary=---WebKitFormBoundaryAczld5sbjrh0FX5q
Accept: application/json
X-Requested-With: XMLHttpRequest
Referer: https://www.olx.ba/objava
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8,ro;q=0.6,de;q=0.4
Cookie: xxxxx

请求有效负载

------WebKitFormBoundaryAczld5sbjrh0FX5q
Content-Disposition: form-data; name="myfile"; filename="2.jpg"
Content-Type: image/jpeg


------WebKitFormBoundaryAczld5sbjrh0FX5q--

我认为上传表单来自dropzone.js,如果这有任何帮助。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

在将图像作为路径卸载之前。尝试将图像转换为字节数组,然后使用Convert.toBase64String方法转换为base64String。然后将base64字符串发布到网站。

感谢。