我正在向几个服务器发送帖子请求。这些服务器返回除一个之外的所有json。其中一人返回如下数据:1fe2 80b9 0800 0000 0000 0400 c3ac c2bd。在C#中发布帖子请求导致奇怪的输出
如果我对剩余的客户端做同样的事情,我从所有服务器上得到有效的Json,但是当我在c#中执行时,其中一台服务器返回那种数据。
我用下面的代码来做到这一点:
public static string MakeRequest(string url, string requestBody, string methodName)
{
string result = "";
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/json";
result = client.UploadString(string.Format("{0}{1}", url, methodName), "POST", requestBody);
}
return result;
}
我也试图与此(旧代码):
public static string MakeRequestA(string url, string requestBody, string methodName)
{
byte[] postBytes = Encoding.ASCII.GetBytes(requestBody);
var request = (HttpWebRequest)WebRequest.Create(string.Format("{0}{1}", url, methodName));
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version11;
request.Method = "POST";
request.ContentType = "application/json";
request.Accept = "text/plain";
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
WebResponse response = request.GetResponse();
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
var dataStream = response.GetResponseStream();
var reader = new StreamReader (dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
我真的不能给你的服务器URL,因为它们是私人的。任何人都知道为什么我得到这些数据而不是有效的json?
您可能需要将用户代理和主机添加到请求的标头中。最近我使用了一个Web服务,如果没有合适的用户代理,它将无法处理请求。 –
获取[Fiddler](http://www.telerik.com/fiddler)分析器并查看两种情况下发送给服务器的内容,然后您将能够看到差异。 – trailmax
确实,您可能需要添加更多标题,尽管我不确定它是哪一个。有关列表,请参阅此处:https://www.soapui.org/testing-dojo/best-practices/understanding-rest-headers-and-parameters.html –