如何使用C#中的WebClient将参数发布到Azure服务URL
本文关键字:Azure 服务 URL 参数 何使用 中的 WebClient | 更新日期: 2023-09-27 18:29:51
我已经测试/搜索了几个小时,了解如何将C#中的参数POST到Azure服务,但没有得到错误405。
使用Chilkat lib的C++中的以下代码运行良好
CkHttp http;
CkHttpRequest req;
http.put_SessionLogFilename("c:/temp/httpLog.txt");
req.put_HttpVerb("POST");
req.put_Path("/api/test?value=1234");
CkHttpResponse *resp = http.SynchronousRequest("http://testservice.cloudapp.net",80,false,req);
if (resp == 0 )
afxDump << http.lastErrorText() << "'r'n";
afxDump << resp->bodyStr() << "'r'n";
delete resp;
但是如果它使用这个c#代码,我会得到错误405。
string uri = "http://testservice.cloudapp.net/api/test";
string parameter = "value=1234";
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string HtmlResult = wc.UploadString(uri, parameter);
}
有没有暗示我做错了什么?
您最好使用HttpClient
而不是WebClient
。通过观察C++代码的作用,在C#中使用HttpClient
应该是这样的
public void Test() {
using (HttpClient client = new HttpClient()) {
client.BaseAddress = new Uri("http://testservice.cloudapp.net");
var response = client.PostAsync("api/test?value=1234", new StringContent(string.Empty)).Result;
var statusCode = response.StatusCode;
var errorText = response.ReasonPhrase;
// response.EnsureSuccessStatusCode(); will throw an exception if status code does not indicate success
var responseContentAsString = response.Content.ReadAsStringAsync().Result;
var responseContentAsBYtes = response.Content.ReadAsByteArrayAsync().Result;
}
}
这是上面代码的异步版本
public async Task TestAsync() {
using (HttpClient client = new HttpClient()) {
client.BaseAddress = new Uri("http://testservice.cloudapp.net");
var response = await client.PostAsync("api/test?value=1234", new StringContent(string.Empty));
var statusCode = response.StatusCode;
var errorText = response.ReasonPhrase;
// response.EnsureSuccessStatusCode(); will throw an exception if status code does not indicate success
var responseContentAsString = await response.Content.ReadAsStringAsync();
var responseContentAsBYtes = await response.Content.ReadAsByteArrayAsync();
}
}