简体   繁体   English

C#httpclient获得响应

[英]C# httpclient get response

I used httpClient to send data to the server. 我使用httpClient将数据发送到服务器。 I can check the response successfully, but my response string is in a php file. 我可以成功检查响应,但是响应字符串在php文件中。 I don't know how to access this string in php with something like: 我不知道如何用类似这样的方式在php中访问此字符串:

if user exist echo true; 
else echo false;

I tried with WebClient class. 我尝试了WebClient类。 It worked but I was unable to check if it's response is successful. 它有效,但是我无法检查它的响应是否成功。

Here is the code: 这是代码:

public Boolean authorization(String korisnik, String zaporka)
{
     var client = new HttpClient();

     var pairs = new List<KeyValuePair<string, string>>
     {
         new KeyValuePair<string, string>("korisnik", korisnik),
         new KeyValuePair<string, string>("zaporka", zaporka)
     };

     var content = new FormUrlEncodedContent(pairs);

     var response = client.PostAsync("http://www.etfos.unios.hr/~tsapina/autorizacija.php", content).Result;
     System.Diagnostics.Debug.WriteLine(response);
     if (response.IsSuccessStatusCode)
     {
          MessageBox.Show("success respond");
          return false;
      }
     return true;
}

I need to get result in a php file output. 我需要在php文件输出中得到结果。

You want to check the Content has value, then ReadAsStringAsync() for the content. 您要检查Content是否有值,然后检查Content ReadAsStringAsync() It's JSON though, so you'll need to parse it. 它是JSON,因此您需要对其进行解析。

Here, I use JsonConvert.Serialize<Dictionary<string,string>>() from Json .NET to deserialize the JSON to a Dictionary<string, string> object, which you can use to access the data. 在这里,我使用来自Json .NET的 JsonConvert.Serialize<Dictionary<string,string>>()将JSON反序列化为Dictionary<string, string>对象,您可以使用该对象访问数据。 May I also suggest using async and await to make use of asynchronous functions properly: 我还可以建议使用asyncawait正确使用异步函数:

public async bool Authorization(string korisnik, string zaporka){
    ...
    try {
        //will always throw an exception if not successful
        response.EnsureSuccessStatusCode();

        var response = await client.PostAsync("http://www.etfos.unios.hr/~tsapina/autorizacija.php", content);

        if (httpResponse.Content != null) {
            var responseContent = await httpResponse.Content.ReadAsStringAsync();

            var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseContent);

            Console.WriteLine(dict["post_var_key"]);
        }
    }
    catch (Exception ex) {
        Console.WriteLine("Error occured: " + ex.Message);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM