WebRequest properties

Peter Volz 1,295 Reputation points
2023-03-28T12:41:15.4133333+00:00

Hello,

I've chosen WebRequest over WebClient to be able to use the POST method, but there are 2 properties missing from WebRequest:

.Encoding

.Headers.Add("user-agent", "Mozilla/5.0.....")

Encoding does not exist at all, so can't set UTF8 or ASCII

While the 2nd line will compile, but at runtime I will get error; to set user-agent use the proper method! How's that?

Thanks everyone.

update: using:

Dim wr As WebRequest = WebRequest.Create(strURI)

WebRequest.Create will make HttpWebRequest, but these properties are not available to me:

.HaveResponse

.TransferEncoding

.UserAgent

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,570 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Sedat SALMAN 13,160 Reputation points
    2023-03-28T19:52:02.7833333+00:00

    If you need to set the user agent, you can cast the WebRequest to HttpWebRequest and set the UserAgent property. Here is an example:

    Dim wr As HttpWebRequest = DirectCast(WebRequest.Create(strURI), HttpWebRequest)
    wr.UserAgent = "Mozilla/5.0....."
    

    As for the encoding, you can cast the response to HttpWebResponse and get the Encoding property from there. Here is an example:

    Dim response As HttpWebResponse = DirectCast(wr.GetResponse(), HttpWebResponse)
    Dim sr As New StreamReader(response.GetResponseStream(), response.Encoding)
    Dim responseText As String = sr.ReadToEnd()
    

    Note that the response's encoding might not be the same as the request's encoding, so you might want to check for that.

    0 comments No comments