C #: WebClient scarica il codice sorgente di una pagina html invece della risorsa reale

StackOverflow https://stackoverflow.com/questions/6310050

  •  26-10-2019
  •  | 
  •  

Domanda

ho adottato questo codice da uno dei blog MSDN e webclient aggiunto per scaricare una risorsa ..

string formUrl = "My login url";
            string formParams = string.Format("userName={0}&password={1}&x={2}&y={3}&login={4}", "user", "password","0","0","login");
            string cookieHeader;
            WebRequest req = WebRequest.Create(formUrl);
            req.ContentType = "application/x-www-form-urlencoded";
            req.Method = "POST";
            byte[] bytes = Encoding.ASCII.GetBytes(formParams);
            req.ContentLength = bytes.Length;
            using (Stream os = req.GetRequestStream())
            {
                os.Write(bytes, 0, bytes.Length);
            }
            WebResponse resp = req.GetResponse();
            cookieHeader = resp.Headers["Set-cookie"];
            string pageSource;
            string getUrl = "Resource url";
            WebRequest getRequest = WebRequest.Create(getUrl);
            getRequest.Headers.Add("Cookie", cookieHeader);
            WebResponse getResponse = getRequest.GetResponse();
            using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
            {
                pageSource = sr.ReadToEnd();
                System.Console.WriteLine(sr.ToString());
            }

            WebClient wc = new WebClient();
            wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";

            wc.DownloadFile("Resource url","C:\\abc.tgz");
            Console.Read();

Ma abc.tgz non è quello che dovrebbe essere. Così, quando ho aperto utilizzando il Blocco note, ho notato che è il file di origine del "mio login URL" pagina .. Dove sto andando male?

C'è qualche proprietà del WebClient che posso usare per vedere l'errore .. cioè .. indirizzo di base ecc?

È stato utile?

Soluzione

rendere le cose più semplici di Let, va bene:

public class CookiesAwareWebClient : WebClient
{
    public CookieContainer CookieContainer { get; private set; }

    public CookiesAwareWebClient()
    {
        CookieContainer = new CookieContainer();
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address);
        ((HttpWebRequest)request).CookieContainer = CookieContainer;
        return request;
    }
}

class Program
{
    static void Main()
    {
        using (var client = new CookiesAwareWebClient())
        {
            var values = new NameValueCollection
            {
                { "userName", "user" },
                { "password", "password" },
                { "x", "0" }, // <- I doubt the server cares about the x position of where the user clicked on the image submit button :-)
                { "y", "0" }, // <- I doubt the server cares about the y position of where the user clicked on the image submit button :-)
                { "login", "login" },
            };

            // We authenticate first
            client.UploadValues("http://example.com/login", values);

            // Now we can download
            client.DownloadFile("http://example.com/abc.tgz", @"c:\abc.tgz");
        }
    }
}

E dal modo in cui il problema con il codice è che non sta passando il cookie di autenticazione rilasciato dal server quando hai inviato la prima richiesta alla seconda richiesta che si suppone di accedere a una risorsa protetta. Tutto quello che passa è un certo tipo di contenuto e non di cookie e tutti. I server come i biscotti: -)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top