未能从get请求获得响应

本文关键字:响应 请求 get | 更新日期: 2023-09-27 18:26:13

所以我对C#真的很生疏。我正在尝试执行一个GET http请求,但我的响应总是空白/空。这是我的代码

    class ServerUtil
{
    String status = "";
    public String serverMessage(String query)
    {
        serverMessageHelper(query);
        return status;
    }
    private async void serverMessageHelper(String query)
    {
        UriBuilder baseUri = new UriBuilder("http://darksync-anarchysystems.rhcloud.com/ServletExample/ServletExample?");
        baseUri.Query = baseUri.Query.Substring(1) + query;
        string url = baseUri.Uri.ToString();
        var httpClient = new HttpClient(new HttpClientHandler());
        HttpResponseMessage response = await httpClient.GetAsync(url);
        try
        {
            response.EnsureSuccessStatusCode();
            status = await response.Content.ReadAsStringAsync();
        }
        catch
        {
            status = "505";
        }
    }

}

我创建了一个ServerUtil对象,并在代码中进行服务器调用

ServerUtil s = new ServerUtil();
string resp = s.serverMessage("action=login&user=" + username + "&password=" + password);

奇怪的是,它在我的服务器上进行了更改,但没有响应。。

未能从get请求获得响应

我已经测试了以下内容,并正确地获得了状态响应。

class ServerUtil
{
    public string ServerMessage(string query)
    {
        return ServerMessageHelperAsync(query).GetAwaiter().GetResult();
    }
    public async Task<string> ServerMessageAsync(string query)
    {
        return await ServerMessageHelperAsync(query);
    }
    private async Task<string> ServerMessageHelperAsync(string query)
    {
        var baseUri = new UriBuilder("http://darksync-anarchysystems.rhcloud.com/ServletExample/ServletExample");
        baseUri.Query = query;
        using (var httpClient = new HttpClient(new HttpClientHandler()))
        {
            try
            {
                using (var response = await httpClient.GetAsync(baseUri.Uri).ConfigureAwait(false))
                {
                    response.EnsureSuccessStatusCode();
                    return await response.Content.ReadAsStringAsync();
                }
            }
            catch
            {
                return "505";
            }
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        var username = "xxx";
        var password = "xxx";
        var s = new ServerUtil();
        //var resp = s.ServerMessageAsync("action=login&user=" + username + "&password=" + password).GetAwaiter().GetResult();
        var resp = s.ServerMessage("action=login&user=" + username + "&password=" + password);
    }
}