簡體   English   中英

HttpClient PutAsync使用RestAPI更新字段

[英]HttpClient PutAsync to update a field using RestAPI

我們有一個第三方API,同時具有GET和PUT方法。第三方API返回響應並僅接受XML。 api看起來像https://bh.org/api/v2/prj/A152 ,它返回的GET

<prj:prj uri="https://bh.org/api/v2/prj/V51" lid="V51" xmlns:udf="http://ge.com/ri/userdefined" xmlns:ri="http://ge.com/ri" xmlns:file="http://ge.com/ri/file" xmlns:prj="http://ge.com/ri/prj">
<name>fgfgfg</name>
<res uri="https://bh.org/api/v2/res/19"/>
<udf:type name="cis"/>
<udf:field type="String" name="ST">Cli</udf:field>
<udf:field type="String" name="CPN">TestName</udf:field>
<udf:field type="Numeric" name="No">1</udf:field>
<udf:field type="String" name="CA">Do not know</udf:field>
<udf:field type="String" name="Cto">Me</udf:field>
<udf:field type="String" name="Site">GT</udf:field>
</prj:prj>

我需要使用第三方API中的put方法將此處的名稱從ad-93更改為ABCD。 我已經創建了應用程序,我們使用GET方法調用第三方API以獲取響應

 using (var client_Name = new HttpClient())
 {
  ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
  Uri uri = new Uri(BaseURL_C);
  client_Name.BaseAddress = uri;
  client_Name.DefaultRequestHeaders.Accept.Clear();
  client_Name.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
  client_Name.DefaultRequestHeaders.Authorization = new   System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray_C));

  string c_URL = BaseURL_C + "api/v2/prj/" + Name;
  var response_LabURL = client_Name.GetAsync(c_URL).Result;
  string responseString_URL = response_LabURL.Content.ReadAsStringAsync().Result;
  XDocument new_doc = XDocument.Parse(responseString_URL);
  new_doc.Descendants("name").FirstOrDefault().Value = serviceResponse;

通過上面的代碼,我可以更改作為響應檢索到的XDocument中名稱的值。 現在,我嘗試將XDocument作為參數傳遞給putAsync,以使用Rest API修改字段。

 using (var putClient = new HttpClient())
 {
 var requestUrl = string c_URL = BaseURL_C + "api/v2/prj/" + Name;;
 using (HttpContent httpContent = new XDocument(new_doc))
  {
    httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/xml");
    HttpResponseMessage response = httpClient.PutAsync(requestUrl, httpContent).Result;
  }

但是上面的代碼會引發錯誤,例如Cannot implicitly convert type 'System.Xml.Linq.XDocument' to 'System.Net.Http.HttpContent'

我不確定如何將XDocument new_doc隱藏到HtppContent中,以便將它們作為參數傳遞。

你必須用這樣的東西

HttpContent httpContent = new StringContent(new_doc.ToString(), Encoding.UTF8, "application/xml");

並刪除線

httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/xml");

暫無
暫無

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

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