首先我使用postman测试工具,测试接口,返回结果正常,如下图
然而,我使用c#后台代码去访问这个接口,却不能获取返回值,最终的返回结果却是空字符串,代码如下
HttpWebRequest request = null;
HttpWebResponse response = null;
Stream streamResponse = null;
try
{
request = (HttpWebRequest)WebRequest.Create("http://192.168.2.20:8080/api/v1/auth/login");
request.Method = "Post";
request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
request.KeepAlive = true;
request.ProtocolVersion = HttpVersion.Version10;
string jsonContract = "{ \"password\" : \"ZJHzjh800521@1\"}";
byte[] PostData = Encoding.UTF8.GetBytes(jsonContract);
//发送数据 using结束代码段释放
using (Stream requestStm = request.GetRequestStream())
{
requestStm.Write(PostData, 0, PostData.Length);
}
ServicePoint currentServicePoint = request.ServicePoint;
currentServicePoint.ConnectionLimit = 1000;
//响应
response = (HttpWebResponse)request.GetResponse();
streamResponse = response.GetResponseStream();
string strResponse = string.Empty;
//如果服务端采用了GZIP压缩,则先解压缩。
if (response.ContentEncoding.ToLower().Contains("gzip"))
{
using (GZipStream gz = new GZipStream(streamResponse, CompressionMode.Decompress))
{
using (StreamReader readerGzip = new StreamReader(gz, Encoding.UTF8))
{
strResponse = readerGzip.ReadToEnd();
}
}
}
else
{
using (StreamReader streamRead = new StreamReader(streamResponse, Encoding.UTF8))
{
strResponse = streamRead.ReadToEnd();
}
}
return strResponse;**//这里的值最后还是空的**
}
catch (Exception ex)
{
var msg = ex.Message;
return msg;
}
请教:我的代码是在哪里出问题了呢,或者还有什么地方没有设置好?怎样才能实现像postman的那种效果,成功返回结果