.Net C #: reading attachments from HttpWebResponse

Can I read an image attachment from System.Net.HttpWebResponse ?

I have a link to a Java page that generates images.

When I open the URL in Firefox, a download dialog appears. The content type is application / png.
Seems to work.

When I try to do this in c # and make a GET request, I get the content type: text / html and without a content location header.

Simple code:

 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 

response.GetResponseStream() empty.

The attempt with Java was successful.

Do I need to prepare a web request or something else?

+5
source share
2 answers

You may need to set the User-Agent header.

Run Fiddler and compare the queries.

+5
source

Writing something to the UserAgent property of HttpWebRequest really matters in many cases. A common practice for web services is to ignore requests with an empty UserAgent . See: Webmasters: Interpreting an Empty User Agent

Just set the UserAgent property UserAgent non-empty string . For example, you can use your application name, build information, impersonate a generic UserAgent, or something else that identifies.

Examples:

 request.UserAgent = "my example program v1"; 
 request.UserAgent = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name.ToString()} v{System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()}"; 
 request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"; 

And just give a complete working example:

 using System.IO; using System.Net; void DownloadFile(Uri uri, string filename) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri); request.Timeout = 10000; request.Method = "GET"; request.UserAgent = "my example program v1"; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (Stream receiveStream = response.GetResponseStream()) { using (FileStream fileStream = File.Create(filename)) { receiveStream.CopyTo(fileStream); } } } } 
0
source

Source: https://habr.com/ru/post/1306268/


All Articles