繁体   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