11

我想在 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)错误请求。

如果我更改请求凭据并在标头中添加身份验证:

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 绑定?

所有意见或指导将不胜感激。

4

4 回答 4

12

HTTP Basic 身份验证要求“Basic”之后的所有内容都进行 Base64 编码,因此请尝试

request.Headers["Authorization"] = "Basic " + 
    Convert.ToBase64String(Encoding.ASCII.GetBytes(authInfo));
于 2011-03-01T11:08:36.587 回答
10

我的问题的解决方案是更改ContentType属性。如果我将 ContentType 更改为

request.ContentType = "text/xml";

如果我在最后一个示例中像Anton Gogolev建议的那样将authInfo转换为 Base64String ,则该请求在这两种情况下都有效。

于 2011-03-02T10:24:26.750 回答
2

使用:

request.ContentType = "application/xml";

request.Credentials = new NetworkCredential(GEOSERVER_USER, GEOSERVER_PASSWD);

也有效。第二个设置认证信息。

于 2012-06-21T12:51:16.200 回答
0

或者,如果你想使用 HttpClient:

 var authValue = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes("admin:geoserver")));
        try
        {
            var client = new HttpClient()
            {
                DefaultRequestHeaders = { Authorization = authValue }
            };

            string url = "http://{BASE_URL}";
            client.BaseAddress = new Uri(url);

            var content = new StringContent("<workspace><name>TestTestTest</name></workspace>",
                 Encoding.UTF8, "text/xml");
            var response = await client.PostAsync($"/{PATH_TO_API}/", content);
            response.EnsureSuccessStatusCode();
            var stringResponse = await response.Content.ReadAsStringAsync();
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine(ex.Message);
        }
于 2019-09-30T20:20:29.613 回答