Question: HttpClient PutAsync to update a field using RestAPI


HttpClient PutAsync to update a field using RestAPI

Answers 1
Added at 2017-01-05 04:01

We have a third party API which has both the GET and PUT methods on it.The third party API returns response and accepts only in XML. The api looks like with the GET it returns

<prj:prj uri="" lid="V51" xmlns:udf="" xmlns:ri="" xmlns:file="" xmlns:prj="">
<res uri=""/>
<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>

I need to change the name here from ad-93 to ABCD using the put method in third party API. I have created applications where we call the third party API using GET method to get the response

 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.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;

With the above code the I am able to change the value of the name in the XDocument that I retrieved as response. Now I am trying to pass the XDocument as a parameter to the putAsync to upadte the field using the 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;

But the above code throws error like Cannot implicitly convert type 'System.Xml.Linq.XDocument' to 'System.Net.Http.HttpContent'

I am not sure how to covert the XDocument new_doc in to HtppContent so to pass them as parameter.

Answers to

HttpClient PutAsync to update a field using RestAPI

nr: #1 dodano: 2017-01-05 04:01

You have to use it something like this

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

and remove the line

httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/xml");
Source Show
◀ Wstecz