Export (0) Print
Expand All

How to: Send an HTTP Request with Proxy 

The .NET Compact Framework supports Web services. This example submits an HTTP GET request with or without a specified proxy.

Example

In the following code example, a button click submits the request and processes the response. The request uses a proxy only if it is specified and uses the WebException class to handle any exceptions. It uses a StreamReader to read the HTML response into a character array buffer.

private void button1_Click(object sender, System.EventArgs e)
{
    
    // Get URL and proxy
    // from the text boxes.
    string url = txtURL.Text;
    string proxy = txtProxy.Text;

    try 
    {
        if(!"".Equals(txtProxy.Text))
        {
            WebProxy proxyObject = new WebProxy(proxy, 80);

            // Disable proxy use when the host is local.
            proxyObject.BypassProxyOnLocal = true;

            // HTTP requests use this proxy information.
            GlobalProxySelection.Select = proxyObject;

        }
        
        WebRequest req = WebRequest.Create(url);
        WebResponse result = req.GetResponse();
        Stream ReceiveStream = result.GetResponseStream();
        Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
        StreamReader sr = new StreamReader( ReceiveStream, encode );

        // Read the stream into arrays of 30 characters
        // to add as items in the list box. Repeat until
        // buffer is read.
        Char[] read = new Char[30];
        int count = sr.Read( read, 0, 30 );
        while (count > 0) 
        {
            String str = new String(read, 0, count);
            lstResults.Items.Add(str);
            count = sr.Read(read, 0, 30);
        }
    } 
    catch(WebException ex)
    {
       string message = ex.Message;
       HttpWebResponse response = (HttpWebResponse)ex.Response;
       if(null != response)
       {
           message = response.StatusDescription;
           response.Close();
       }
       lstResults.Items.Add(message);              
    }
    catch(Exception ex) 
    {
        lstResults.Items.Add(ex.Message);
    }
}

Compiling the Code

This example requires references to the following namespaces:

See Also

Community Additions

ADD
Show:
© 2014 Microsoft