In the following samples, you can find out how to send a HTTP GET request, using C# with authentication and without it. Here we go!

With Authentication (Username&password)

private bool sendData(string url, string user, string pwd, out string detail)
{
    var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
    httpWebRequest.ContentType = "text/json";
    Uri myUri = new Uri(url);
    httpWebRequest.Method = "GET";
    NetworkCredential myNetworkCredential = new NetworkCredential(user, pwd);
    CredentialCache myCredentialCache = new CredentialCache();
    myCredentialCache.Add(myUri, "Basic", myNetworkCredential);
    httpWebRequest.PreAuthenticate = true;
    httpWebRequest.Credentials = myCredentialCache;

    try
    {
        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            detail = streamReader.ReadToEnd();
        }
        if (httpResponse.StatusCode == HttpStatusCode.OK)
            return true;
    }
    catch (Exception e)
    {
        detail = e.ToString();
    }
    return false;
}

And without Authentication (Username&password)

private bool sendData(string url, out string detail)
{
    var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
    httpWebRequest.ContentType = "text/json";
    Uri myUri = new Uri(url);
    httpWebRequest.Method = "GET";
    try
    {
        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            detail = streamReader.ReadToEnd();
        }
        if (httpResponse.StatusCode == HttpStatusCode.OK)
            return true;
    }
    catch (Exception e)
    {
        detail = e.ToString();
    }
    return false;
}
Advertisements