我想在c#中执行以下cURL请求:
curl -u admin:geoserver -v -XPOST -H 'Content-type: text/xml' \
-d '<workspace><name>acme</name></workspace>' \
http://localhost:8080/geoserver/rest/workspaces我尝试过使用WebRequest:
string url = "http://localhost:8080/geoserver/rest/workspaces";
WebRequest request = WebRequest.Create(url);
request.ContentType = "Content-type: text/xml";
request.Method = "POST";
request.Credentials = new NetworkCredential("admin", "geoserver");
byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes("<workspace><name>my_workspace</name></workspace>");
Stream reqstr = request.GetRequestStream();
reqstr.Write(buffer, 0, buffer.Length);
reqstr.Close();
WebResponse response = request.GetResponse();
...但我得到一个错误:(400) Bad request。
如果我更改了请求凭据并在header中添加了身份验证:
string url = "http://localhost:8080/geoserver/rest/workspaces";
WebRequest request = WebRequest.Create(url);
request.ContentType = "Content-type: text/xml";
request.Method = "POST";
string authInfo = "admin:geoserver";
request.Headers["Authorization"] = "Basic " + authInfo;
byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes("<workspace><name>my_workspace</name></workspace>");
Stream reqstr = request.GetRequestStream();
reqstr.Write(buffer, 0, buffer.Length);
reqstr.Close();
WebResponse response = request.GetResponse();
...然后我得到:(401)未授权。
我的问题是:我应该使用另一个C#类,比如WebClient或HttpWebRequest,还是必须为.NET使用curl绑定?
所有的意见或指导将不胜感激。
发布于 2011-03-02 18:24:27
我的问题的解决方案是更改ContentType属性。如果我将ContentType更改为
request.ContentType = "text/xml";如果我还像Anton Gogolev建议的那样,在上一个示例中将authInfo转换为Base64String,则该请求在两种情况下都有效。
发布于 2011-03-01 19:08:37
HTTP基本身份验证将"Basic“之后的所有内容都重新编码为base64编码,因此请尝试
request.Headers["Authorization"] = "Basic " +
Convert.ToBase64String(Encoding.ASCII.GetBytes(authInfo));发布于 2012-06-21 20:51:16
使用:
request.ContentType = "application/xml";
request.Credentials = new NetworkCredential(GEOSERVER_USER, GEOSERVER_PASSWD);也是有效的。第二个设置身份验证信息。
https://stackoverflow.com/questions/5152723
复制相似问题