我正在使用一个使用基本身份验证的REST Web服务,并返回一个XML字符串。这是我用来获取数据并将其作为XDocument返回的方法:
var req = (HttpWebRequest)WebRequest.Create(uri);
String readToEnd;
const string postData = "";
var encoding = new ASCIIEncoding();
byte[] byte1 = encoding.GetBytes(postData);
req.Method = "POST";
req.Timeout = 10000;
req.ContentType = "text/XML";
req.ContentLength = byte1.Length;
string authInfo = userName + ":" + password;
authInfo = Convert.ToBase64String(Encoding.UTF8.GetBytes(authInfo));
req.Headers["Authorization"] = "Basic " + authInfo;
var newStream = req.GetRequestStream();
newStream.Write(byte1, 0, byte1.Length);
newStream.Close();
try
{
var resp = req.GetResponse();
var answer = resp.GetResponseStream();
var _answer = new StreamReader(answer);
readToEnd = _answer.ReadToEnd();
answer.Close();
}
catch (Exception ex)
{
readToEnd = null;
}
return readToEnd != null ? XDocument.Parse(readToEnd) : null;
现在稍后,我操纵了那个xml,我准备把它发回给另一个uri。我认为它可能是相同的代码,除了可能将我的新XML字符串放在变量'postData'中?
这是将xml字符串发布到网络服务的正确方法吗?我已经看过了,但在使用基本授权时似乎无法对此有所了解。
答案 0 :(得分:1)
我做了以下事情。关键是您必须在发布之前将数据写入请求流。希望它有所帮助。
var request = CreateBaseRequest(body);
HttpWebResponse WebResp = (HttpWebResponse)request.GetResponse();
Stream Answer = WebResp.GetResponseStream();
StreamReader response = new StreamReader(Answer);
var r = response.ReadToEnd();
static HttpWebRequest CreateBaseRequest(string postData)
{
var req = (HttpWebRequest)HttpWebRequest.Create(@"https://xyz.com/");
req.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
req.Method = "POST";
req.KeepAlive = true;
byte[] buffer = Encoding.ASCII.GetBytes(postData);
req.ContentLength = buffer.Length;
Stream PostData = req.GetRequestStream();
PostData.Write(buffer, 0, buffer.Length);
PostData.Close();
return req;
}