package Microsoft.Samples.QuickStart.HowTo.Net.WebRequests;
//-----------------------------------------------------------------------
//  This file is part of the Microsoft .NET Framework SDK Code Samples.
// 
//  Copyright (C) Microsoft Corporation.  All rights reserved.
// 
// This source code is intended only as a supplement to Microsoft
// Development Tools and/or on-line documentation.  See these other
// materials for detailed information regarding Microsoft code samples.
// 
// THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//-----------------------------------------------------------------------
import System.*;
import System.Net.*;
import System.IO.*;
import System.Text.*;
import System.Web.*;

final class ClientPost
{
    public static void main(String[] args)
    {
        if (args.get_Length() < 1)
        {
            ShowUsage();
        }
        else
        {
            if (args.get_Length() < 2)
            {
                GetPage(args[0], "s1=food&s2=bart");
            }
            else
            {
                GetPage(args[0], args[1]);
            }
            Console.WriteLine();
            Console.WriteLine("Press any key to continue...");
            Console.ReadLine();
        }
        return;
    } //main

     private static void ShowUsage()
    {
        Console.WriteLine("Attempts to POST into to a URL");
        Console.WriteLine();
        Console.WriteLine("Usage:");
        Console.WriteLine("ClientPost URL [postdata]");
        Console.WriteLine();
        Console.WriteLine("Examples:");
        Console.WriteLine("ClientPost http://www.microsoft.com s1=food&s2=bart");
    } //ShowUsage

    private static void GetPage(String url, String payload)
    {
        Stream requestStream = null;
        WebResponse response = null;
        StreamReader reader = null;
        try {
            WebRequest request = WebRequest.Create(url);
            request.set_Method(WebRequestMethods.Http.Post);
            request.set_ContentType("application/x-www-form-urlencoded");
            StringBuilder urlEncoded = new StringBuilder();
            char reserved[] =  { '?', '=', '&' };
            ubyte byteBuffer[] = null;

            if (payload != null) {
                int i = 0;
                int j;
                while (i < payload.get_Length()) {
                    j = payload.IndexOfAny(reserved, i);
                    if (j == -1) {
                        urlEncoded.Append(HttpUtility.UrlEncode(
                            payload.Substring(i, payload.get_Length() - i)));
                        break;
                    }
                    urlEncoded.Append(HttpUtility.UrlEncode(
                        payload.Substring(i, j - i)));
                    urlEncoded.Append(payload.Substring(j, 1));
                    i = j + 1;
                }
                byteBuffer = Encoding.get_UTF8().GetBytes(urlEncoded.ToString());
                request.set_ContentLength(byteBuffer.get_Length());
                requestStream = request.GetRequestStream();
                requestStream.Write(byteBuffer, 0, byteBuffer.get_Length());
                requestStream.Close();
            }
            else {
                request.set_ContentLength(0);
            }
            response = request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            reader = new StreamReader(responseStream);
            Console.WriteLine("\r\nResponse stream received");
            char charBuffer[] = new char[256];
            int count = reader.Read(charBuffer, 0, charBuffer.length);
            Console.WriteLine("HTML...\r\n");
            while (count > 0) {
                Console.Write(new String(charBuffer, 0, count));
                count = reader.Read(charBuffer, 0, charBuffer.length);
            }
            Console.WriteLine("");
        }
        catch (UriFormatException exp)
        {
            Console.WriteLine("\r\nThe request URI was malformed");
        }
        catch (WebException exp)
        {
            Console.WriteLine("\r\nThe request URI could not be found.");
        }
        catch (IOException exp)
        {
            Console.WriteLine("\r\nThe request URI could not be retrieved");
        }
        finally
        {
            if (requestStream != null)
                requestStream.Close();
            if (response != null)
                response.Close();
            if (reader != null)
                reader.Close();
        }
    } //GetPage
} //ClientPost