2016/07/28

C#.Net 透過HttpClient取得Content

程式碼:
using System;
using System.Net.Http;
using System.Windows.Forms;

namespace Test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            string url = @"http://yahoo.com.tw";
            ShowContent(url);
        }

        private async void ShowContent(String url = "")
        {
            if (String.IsNullOrEmpty(url))
                return;
            var client = new HttpClient();
            var msg = await client.GetAsync(url);
            var content = msg.Content;
            var code = msg.StatusCode;
            if (code == System.Net.HttpStatusCode.OK)
            {
                var result = await content.ReadAsStringAsync();
                Console.WriteLine(result);
            }
        }

    }
}

執行結果:

沒有留言:

張貼留言