14.5. Communicating with a Web Server
Problem
You want to send a request to a web server in the form of a GET or POST request. After you send the request to a web server, you want to get the results of that request (the response) from the web server.
Solution
Use the HttpWebRequest class in conjunction with the WebRequest class to create and send a request to a server.
Take the Uri of the resource, the method to use in the request (GET or POST), and the data to send (only for POST requests), and use this information to create an HttpWebRequest, as shown in Recipe 14.5.
Example 14-2. Communicating with a web server
using System.Net;
using System.IO;
using System.Text;
public static HttpWebRequest GenerateHttpWebRequest(Uri uri)
{
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(uri);
return httpRequest;
}
// POST overload
public static HttpWebRequest GenerateHttpWebRequest(Uri uri,
string postData,
string contentType)
{
HttpWebRequest httpRequest = GenerateHttpRequest(uri);
byte[] bytes = Encoding.UTF8.GetBytes(postData);
httpRequest.ContentType = contentType;
//"application/x-www-form-urlencoded"; for forms
httpRequest.ContentLength = postData.Length;
using (Stream requestStream = httpRequest.GetRequestStream( ))
{
requestStream.Write(bytes, 0, bytes.Length);
}
return httpRequest;
}Once you have an HttpWebRequest, you send the request and get the response using the GetResponse method. It takes the newly created HttpWebRequest as input and returns an HttpWebResponse. The ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access