用户名和密码获取Json

时间:2013-10-05 17:44:22

标签: c# json task

在一个胜利应用程序中,我想从一个带有用户名和密码的URL获取一个Json,并在一个富文本框中显示Json。我使用下面的代码,但“myMethod()”方法一直在等待?!我的代码有什么问题? 我使用.net 4.5 谢谢......

async static Task<dynamic> myMethod()
        {
            NetworkCredential credentials = new NetworkCredential("username", "password");
            var handler = new HttpClientHandler { Credentials = credentials, AllowAutoRedirect = true };
            HttpClient client = new HttpClient(handler);
            client.DefaultRequestHeaders.Add("User-Agent" ,"Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12");
            var responseString = await client.GetStringAsync("http://myURL.php");
            dynamic stuff = Newtonsoft.Json.JsonConvert.DeserializeObject(responseString
            return stuff ;        }
 private void button2_Click(object sender, EventArgs e)
        {
            dynamic d=myMethod().Result;
            richTextBox1.Text = d.ToString();
        }

2 个答案:

答案 0 :(得分:0)

您可能想要更改button2_click方法,如下所示:

 private async void button2_Click(object sender, EventArgs e)
{
    dynamic d= await myMethod();
    richTextBox1.Text = d.ToString();
}

或更改

await client.GetStringAsync("http://myURL.php");

client.GetStringAsync("http://myURL.php").Result;

答案 1 :(得分:0)

工作原理:

string URI = "http://url.php";
        string myParameters = "username=myUsername&password=myPassword";
        using (WebClient wc = new WebClient())
        {
            wc.Headers[HttpRequestHeader.ContentType] =
            "application/x-www-form-urlencoded";
            string HtmlResult = wc.UploadString(URI, myParameters);
            dynamic stuff1 = Newtonsoft.Json.JsonConvert.DeserializeObject(HtmlResult);
        }