如何将值与Json post xamarin.forms进行比较

时间:2016-08-11 05:42:20

标签: c# rest dotnet-httpclient

我想使用JSON Post方法发布用户名和密码,以便我能够登录并获取令牌但是我遇到了一些问题。

public async Task<string> GetActionResult(string url)
    {
        Uri geturi = new Uri("http://172.20.129.193/NYPStudentLifeService/" + url);
        var client = new HttpClient();
        HttpResponseMessage responseGet = await client.PostAsync();
        responseGet.EnsureSuccessStatusCode();
        string content = await responseGet.Content.ReadAsStringAsync();
        return content;
    }

样本体参数Json

{
"AdminNo": "sample string 1",
"Password": "sample string 2"
}

1 个答案:

答案 0 :(得分:0)

using Newtonsoft.JSON;

//your login info
LoginInfo li = new LoginInfo(){AdminNo ="John Doe",Password="123456"};

// your response string
string response= await GetStreamAsync("url",li,null);

private async Task<string> GetStreamAsync(string url, object body, Dictionary<string, string> headers)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
     request.Accept = "application/json";
    request.ContentType = "application/json";
    request.Method = "POST";
    if (headers != null)
        foreach (var kv in headers)
            request.Headers[kv.Key] = kv.Value;
    var stream = await request.GetRequestStreamAsync();

    using (var writer = new StreamWriter(stream))
    {
        if (body != null)
            writer.Write(JsonConvert.SerializeObject(body));
        writer.Flush();
        writer.Dispose();
    }

    var response = await request.GetResponseAsync();
    var respStream = response.GetResponseStream();
    using (StreamReader sr = new StreamReader(respStream))
    {
        return sr.ReadToEnd();
    }
}

public class LoginInfo
{
    public string AdminNo{get;set;}
    public string Password{get;set;}
}