본문 바로가기

C#/Network

C# HttpClient RestAPI Post

C# HttpClient RestAPI Post

 

비동기 HttpClient

public static string BaseUrl = "";
 
public static async Task<string> Login(bool isReturnResponseMessage = false)
{
    ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; // 인증
 
    string result = string.Empty;
 
    try
    {
        string id = "";
        string pw = "";
 
        var bytevalue = Encoding.UTF8.GetBytes(id + ":" + pw);
        var base64value = Convert.ToBase64String(bytevalue);
 
        var cl = new HttpClient();
        cl.BaseAddress = new Uri(BaseUrl);
 
        cl.Timeout = TimeSpan.FromSeconds(3);
        cl.DefaultRequestHeaders.Add("accept", "application/json");
        cl.DefaultRequestHeaders.Add("authorization", "Basic " + base64value);
        HttpResponseMessage response = await cl.PostAsync("api/login", null);
 
        if (isReturnResponseMessage)
        {
            return response.ToString();
        }
 
        var jsonString = await response.Content.ReadAsStringAsync();
        dynamic array = JsonConvert.DeserializeObject(jsonString);
        foreach (var item in array)
        {
            if (item.Name == "access_token")
            {
                result = item.Value.Value;
                break;
            }
        }
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
    }
 
    return result;
}

 

 

동기 WebRequest

public string Post(string uri, string postData)
{
    string responseFromServer = string.Empty;

    try
    {
        // Create a request using a URL that can receive a post.
        WebRequest request = WebRequest.Create(uri);
        // Set the Method property of the request to POST.
        request.Method = "POST";

        // Create POST data and convert it to a byte array.
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);

        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/x-www-form-urlencoded;";
        //request.ContentType = "application/x-www-form-urlencoded";
        // Set the ContentLength property of the WebRequest.
        request.ContentLength = byteArray.Length;
        

        // Get the request stream.
        Stream dataStream = request.GetRequestStream();
        // Write the data to the request stream.
        dataStream.Write(byteArray, 0, byteArray.Length);
        // Close the Stream object.
        dataStream.Close();

        // Get the response.
        WebResponse response = request.GetResponse();
        // Display the status.
        //Console.WriteLine(((HttpWebResponse)response).StatusDescription);

        // Get the stream containing content returned by the server.
        // The using block ensures the stream is automatically closed.
        using (dataStream = response.GetResponseStream())
        {
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            responseFromServer = reader.ReadToEnd();
            // Display the content.
            Console.WriteLine(responseFromServer);
        }

        // Close the response.
        response.Close();
    }
    catch(Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }

    return responseFromServer;
}

'C# > Network' 카테고리의 다른 글

C# Ping 테스트, 해당 IP 장치 이름 가져오기  (0) 2020.08.07
C# 네트워크 상 맥어드레스 가져오기  (0) 2020.08.07
C# http post header body  (0) 2020.08.07
C# HttpClient RestAPI Patch  (0) 2020.08.04
C# HttpClient RestAPI Get  (0) 2020.08.03