我一直在为这个问题绞尽脑汁而无法提出一个很好的理由,但是当我运行我的vb.net代码时,它执行得很好。我正在将其重新编写为c#(学习过程),并在GetResponse
行收到“服务器返回500”错误。
非常感谢任何建议!
C#代码 - 已损坏
string SpaceURL = "https://1.1.1.1/api/space/device-management/discover-devices";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(SpaceURL);
request.ContentType = "application/vnd.net.juniper.space.device-management.discover-devices+xml;version=1;charset=UTF-8";
request.Accept = "*/*";
request.Headers.Add("Authorization: Basic authcode");
request.Method = "POST";
//Get the request text for stream writer
CommonFunctions objCF = new CommonFunctions();
string strRequest = objCF.SerializeObject(this,true,false);
StreamWriter sw = new StreamWriter(request.GetRequestStream());
sw.Write(strRequest);
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
return sr.ReadToEnd();
下面的VB.net代码工作正常
Dim url As String
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
url = "https://1.1.1.1/api/space/device-management/discover-devices"
request = DirectCast(WebRequest.Create(url), HttpWebRequest)
request.ContentType = "application/vnd.net.juniper.space.device-management.discover-devices+xml;version=1;charset=UTF-8"
request.Accept = "*/*"
request.Headers.Add("Authorization: Basic authcode=")
request.Method = "POST"
Dim requesttext As String = "<systemDiscoveryRule><ruleName>testdiscovery</ruleName><ipAddressDiscoveryTarget><ipAddress>" & txtIPAddress.Text & "</ipAddress></ipAddressDiscoveryTarget><usePing>true</usePing><useSnmp>false</useSnmp><snmpV1Setting><communityName>nsn-space</communityName></snmpV1Setting><manageDiscoveredSystemsFlag>true</manageDiscoveredSystemsFlag><sshCredential><userName>username</userName><password>password</password></sshCredential><tagNewlyManagedDiscoveredSystemsFlag>true</tagNewlyManagedDiscoveredSystemsFlag><tagForNewlyManagedDiscoveredSystems>store-devices</tagForNewlyManagedDiscoveredSystems></systemDiscoveryRule>"
Dim sw As New System.IO.StreamWriter(request.GetRequestStream)
sw.Write(requesttext)
sw.Dispose()
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New System.IO.StreamReader(response.GetResponseStream())
我还将内联xml与C#版本中创建的XML进行了比较,从序列化一个类对象(更清洁!)
答案 0 :(得分:4)
你能查一下这行
吗?request.Headers.Add("Authorization: Basic authcode');
应该阅读
request.Headers.Add("Authorization: Basic authcode");
引号不匹配。
答案 1 :(得分:1)
正如Adam Houldsworth所说
您不要在VB版本中刷新C#版本的编写器
Dispose
,会调用Close
,然后调用Flush
。该 using statement是你的朋友。不确定这是否是问题所在 request.Headers.Add调用在两者中也有不同的参数 版本