Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

c# - Remote server (403) Forbidden error while using WebClient

I am trying to query some URL using WebClient.

I have a collection which I loop through to get the QueryString value, and build final URL, and then pass it on to client.

The very first time it gets executed well, I get proper response, however, when it goes in loop second time, I get the error:

System.Net.WebException --> The remote server returned an error: (403) Forbidden.

If I get response for very first time. Then I should get for rest of the collection too.

Any clue why? What I might be missing?

Below is the code snippet I am using.

 using(System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:sample.text")) {
    foreach(var f in fileCollections) {
        strFinalURL = string.Empty;

        strFinalURL = "someURL" + f; // f can be considered as querystring param value

        try {
            using(var client = new WebClient()) {

                test = client.DownloadString(strFinalURL);
                if (!test.Contains("somecondition")) {
                    file.WriteLine("");
                }
            }
        } catch (System.Exception ex) {
            Console.WriteLine(ex.Message);
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Some web servers can block requests based on the user agent string they provide. In your case, you send an empty string as a user agent. Try to add the user agent of a browser, any browser would be fine.

For example:

client.Headers.Add("user-agent", " Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0");

For a list of user agents, you can click here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...