0

In a win App I want to get a Json from a url with a username and password and show the Json in a richTextBox.I use the below code but the "myMethod()" method is waiting all the time?! what's wrong in my code? I use .net 4.5 thank you ...

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();
        }
4

2 回答 2

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;
于 2013-10-05T18:54:22.147 回答
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);
        }
于 2013-10-06T19:25:52.513 回答