简体   繁体   English

使用 HTTPClient 调用 REST API 时在 httpResponseMessage 中获取 null

[英]Getting null in httpResponseMessage when calling REST API using HTTPClient

I am trying to execute a REST API which uses HTTP POST.我正在尝试执行使用 HTTP POST 的 REST API。 The API consumes and produces xml content. API 消耗并产生 xml 内容。 I am getting null in httpResponseMessage and no exception is thrown.我在 httpResponseMessage 中得到 null 并且没有抛出异常。 I tried executing the same REST API through HttpWebRequest I am getting the response Below you can find Working and Not Working case.我尝试通过 HttpWebRequest 执行相同的 REST API 我得到了响应下面你可以找到工作和不工作的情况。 Performance wise HttpWebRequest or HTTPClient which is better?性能明智的 HttpWebRequest 或 HTTPClient 哪个更好?

Not Working case HTTPClient不工作的情况下 HTTPClient

try {
    using(var client = new HttpClient()) {
        Console.WriteLine(inputxml);

        var httpContent = new StringContent(inputxml, Encoding.UTF8, "application/xml");

        Uri testUri = new Uri("http://127.0.0.1:8080/rest/services/getDocument");

        var httpResponseMessage = await client.PostAsync(testUri, httpContent);

        Console.WriteLine(httpResponseMessage.Content.ReadAsStringAsync());

        if (httpResponseMessage.StatusCode == HttpStatusCode.OK) {
            var messageContents = await httpResponseMessage.Content.ReadAsStringAsync();

        }
    }

}

Working Case HTTPWebREquest工作案例 HTTPWebREquest

 HttpWebRequest request = (HttpWebRequest) WebRequest.Create("http://127.0.0.1:8080/rest/services/getDocument");
byte[] bytes = Encoding.UTF8.GetBytes(inputxml.ToString());
request.ContentType = "application/xml";
request.ContentLength = bytes.Length;
request.Method = "POST";
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response;
response = (HttpWebResponse) request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK) {
    Stream responseStream = response.GetResponseStream();
    string responseStr = new StreamReader(responseStream).ReadToEnd();
    Console.WriteLine("responseStr " + responseStr);
    return responseStr;
}
return null;
}

You can use RestSharp for sending HTTP Requests.您可以使用 RestSharp 发送 HTTP 请求。 For me, the best and the simplest method for HTTP Communication.对我来说,HTTP 通信的最佳和最简单的方法。

public string SendRequest(String xml)
    {
        string responseMessage= "";
        RestClient restClient;
        restClient = new RestClient("http://127.0.0.1:8080/rest/services/getDocument");
        RestRequest restRequest = new RestRequest(Method.POST);
        restRequest.AddHeader("Accept", "application/xml");
        restRequest.AddHeader("Content-Type", "application/xml");
        restRequest.AddXmlBody(xml);
        IRestResponse restResponse = restClient.Execute(restRequest);
        if (restResponse.StatusCode == HttpStatusCode.OK)
        {
            responseMessage= restResponse.Content;
        }
        return responseMessage;
    }
}

Here:这里:

Console.WriteLine(httpResponseMessage.Content.ReadAsStringAsync());

You're reading the response body, and printing System.Threading.Task 1` to the console.您正在阅读响应正文,并将System.Threading.Task 1` 打印到控制台。 Then the next time you try to read the response body again, its stream is at its end and won't return anything.然后下次您尝试再次读取响应正文时,它的 stream 已结束,不会返回任何内容。

Read the content once, await the call and store the result in a variable.读取内容一次,等待调用并将结果存储在变量中。

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

相关问题 使用HttpResponseMessage时,不会从Web API获得任何响应 - Getting absolutely no response from Web API when using HttpResponseMessage 使用HttpClient连接到API时出现错误 - Getting an error when connecting to an API using HttpClient 异步调用HttpClient以通过Ajax获取HttpResponseMessage - Calling HttpClient asynchronously to get the HttpResponseMessage via ajax 使用httpclient消费时出现无效URI错误 - Invalid URI Error when using httpclient to consume REST API C# REST Api 在我通过 HttpClient 调用 ZDB974238714CA8DE634ACEClient 时总是返回 401 状态码 - C# REST Api always return 401 status code when i am calling API by HttpClient 使用HttpClient和HttpResponseMessage的带有两个字符串的PostAsync - PostAsync with two strings using HttpClient and HttpResponseMessage 使用HttpClient发布并读取HttpResponseMessage状态 - Post using HttpClient & Read HttpResponseMessage status 使用HttpClient在本地主机上调用rest api导致401未经授权的IIS 8.5 - Calling rest api on localhost using HttpClient causing 401 Unauthorized, IIS 8.5 使用HttpResponseMessage.Content.ReadAsStringAsync()时没有得到内容的全部; - Not getting the entirety of the content when using HttpResponseMessage.Content.ReadAsStringAsync(); 通过使用C#和HttpClient调用REST API来检索JSON内容 - Retrieving JSON content by calling a REST API with C# and HttpClient
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM