WebRequest但不是cURL给出错误403

WebRequest但不是cURL给出错误403

本文介绍了C#WebRequest但不是cURL给出错误403的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#中有一个WebRequest,我正试图用它从Instagram检索数据. WebRequest抛出The remote server returned an error: (403) Forbidden.,但是cURL命令返回HTML.实际上,我的POST表单数据会更长,并返回JSON.

I have a WebRequest in C# that I am trying to use to retrieve data from Instagram. The WebRequest throws The remote server returned an error: (403) Forbidden., but a cURL command returns HTML. In practice, my POST form data will be longer and return JSON.

C#

        String uri = "https://www.instagram.com/query/";
        var request = (HttpWebRequest)WebRequest.Create(uri);
        request.Method = "POST";

        string postData = "q=ig_user(1118028333)";
        ASCIIEncoding encoding = new ASCIIEncoding();
        byte[] byte1 = encoding.GetBytes(postData);

        // Set the content type of the data being posted.
        request.ContentType = "application/x-www-form-urlencoded";

        // Set the content length of the string being posted.
        request.ContentLength = byte1.Length;


        using (var dataStream = request.GetRequestStream())
        {
            dataStream.Write(byte1, 0, byte1.Length);
        }

        try
        {
            var x = (HttpWebResponse)request.GetResponse();
        }
        catch (WebException wex)
        {
            String wMessage = wex.Message;
        }

引发错误403.

cURL(在Windows中)

curl "https://www.instagram.com/query/" --data "q=ig_user(1118028333)"

返回HTML.

FireFox请求正文,方法= POST,无标题

q=ig_user(1118028333)

返回HTML

为什么WebRequest会引发错误403,而不是cURL或FireFox?我还可以在C#中做些什么来获取数据?

Why would the WebRequest throw error 403, but not cURL or FireFox? What else can I do in C# to get data?

推荐答案

我认为您感到困惑.我之所以这么认为,是因为我只是尝试对Postman进行同样的操作,虽然我确实得到了HTML响应,但我也得到了403响应状态代码.我认为您可能没有注意cUrl的响应代码.见下文

I think you are getting confused. The reason I assume so, it's because I just tried doing the same with Postman and while I do get an HTML response, I ALSO get 403 response status code. I think you might not be paying attention to cUrl's response code. See below

通常,我尝试使用System.Net.Http.HttpClient类,因此我可以在引发异常之前先检查状态代码,即使响应代码大于400(错误响应)

Normally, I try to use the System.Net.Http.HttpClient class, so I can check the status code first before an exception is thrown and I can even retrieve the response content (if any) even if the response code is greater than 400 (error response)

try
{
    var client = new HttpClient();
    var response = await client.GetAsync(url);

    if (response.IsSuccessStatusCode)
    {
         var json = await response.Content.ReadAsStringAsync();
    }
    else
    {
        string content = null;

        if (response.Content != null)
        {
            content = await response.Content.ReadAsStringAsync();
        }
    }

}
catch (Exception ex){}

这篇关于C#WebRequest但不是cURL给出错误403的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 14:10