我一直在尝试弄清楚如何读取httpclient调用的内容,但似乎无法理解。我得到的响应状态是200,但是我不知道如何获得返回的实际Json,这就是我所需要的!
以下是我的代码:
async Task<string> GetResponseString(string text)
{
var httpClient = new HttpClient();
var parameters = new Dictionary<string, string>();
parameters["text"] = text;
Task<HttpResponseMessage> response =
httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters));
return await response.Result.Content.ReadAsStringAsync();
}
我得到它只是从方法中调用它:
Task<string> result = GetResponseString(text);
这就是我得到的
response Id = 89, Status = RanToCompletion, Method = "{null}", Result = "StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:\r\n{\r\n Connection: keep-alive\r\n Date: Mon, 27 Oct 2014 21:56:43 GMT\r\n ETag: \"5a266b16b9dccea99d3e76bf8c1253e0\"\r\n Server: nginx/0.7.65\r\n Content-Length: 125\r\n Content-Type: application/json\r\n}" System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>
更新:这是根据Nathan在下面的回复中我当前的代码
async Task<string> GetResponseString(string text)
{
var httpClient = new HttpClient();
var parameters = new Dictionary<string, string>();
parameters["text"] = text;
var response = await httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters));
var contents = await response.Content.ReadAsStringAsync();
return contents;
}
我从这种方法调用它。
string AnalyzeSingle(string text)
{
try
{
Task<string> result = GetResponseString(text);
var model = JsonConvert.DeserializeObject<SentimentJsonModel>(result.Result);
if (Convert.ToInt16(model.pos) == 1)
{
_numRetries = 0;
return "positive";
}
if (Convert.ToInt16(model.neg) == 1)
{
_numRetries = 0;
return "negative";
}
if (Convert.ToInt16(model.mid) == 1)
{
_numRetries = 0;
return "neutral";
}
return "";
}
catch (Exception e)
{
if (_numRetries > 3)
{
LogThis(string.Format("Exception caught [{0}] .... skipping", e.Message));
_numRetries = 0;
return "";
}
_numRetries++;
return AnalyzeSingle(text);
}
}
并且它永远运行,var model = JsonConvert.DeserializeObject<SentimentJsonModel>(result.Result);
一次命中
,然后继续运行而没有在另一个断点处停止。
当我暂停执行时,它说
Id =无法优化表达式,因为当前方法的代码已优化。,Status =无法评估表达式,因为当前方法的代码已优化。,Method =无法优化表达式,因为当前方法的代码已优化。由于当前方法的代码已优化,因此无法评估表达式。
..我继续执行,但它永远运行。不确定是什么问题