Search code examples
c#httphttpclienthttpresponse

How do I extract a GET value from a Http response?


I've embedded a http server within a desktop application to be used for catching the response from an OAuth2 redirect. The following method picks up the message and converts it to a string:

private void ReceiveCallback(IAsyncResult ar)
{
    var client = (Socket)ar.AsyncState;
    var size = client.EndReceive(ar);
    var received = new byte[size];

    Array.Copy(Buffer, received, size);
    var data = Encoding.ASCII.GetString(received);

    OnCallback(data);
}

The OnCallback method is an event which passes the data to another class. The content of data looks like the following upon a successful auth call:

GET /?code=CODE_I_NEED_APPEARS_HERE HTTP/1.1
Host: localhost:8321
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,/;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9

How do i extract the code param from the above string (the CODE_I_NEED_APPEARS_HERE value - I removed the actual code as it's an auth token)? I've tried to create a http response message to split the string out into properties, but I can't find a way to retrieve the GET param value:

var response = new HttpResponseMessage();
response.Content = new StringContent(message);

Solution

  • class Program
    {
        public static void Main()
        {
            string input = "GET /?code=CODE_I_NEED_APPEARS_HERE& HTTP/1.1 Host: localhost:8321 Connection: keep-alive Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,/;q=0.8 Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9";
            string output = GetCode(input);
            Console.WriteLine(output);
            Console.ReadLine();
        }
    
        private static readonly Regex Pattern = new Regex(@"code=([^&\s]+)", RegexOptions.Compiled);
    
        public static string GetCode(string input)
        {
            var value = Pattern.Match(input);
            return value.Groups[1].Value;
        }
    }
    

    the output should be the value of the code param