簡體   English   中英

如何在C#中使用WebClient將參數發布到Azure服務URL

[英]How to post parameter to Azure Service URL using WebClient in C#

我已經測試/搜索了數小時,以了解如何在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 ++代碼的作用,它應該使用HttpClient在C#中是這樣的

    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();
        }

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM