简体   繁体   中英

C# httpclient get response

I used httpClient to send data to the server. I can check the response successfully, but my response string is in a php file. I don't know how to access this string in php with something like:

if user exist echo true; 
else echo false;

I tried with WebClient class. 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.

You want to check the Content has value, then ReadAsStringAsync() for the content. It's JSON though, so you'll need to parse it.

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. May I also suggest using async and await to make use of asynchronous functions properly:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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