I am trying to call a Windchill Odata rest service. THE HTTP GET method works fine, but it is not working as expected when making a POST request. I am also not sure how to pass the required parameter to the URL. Any suggestions will help a lot.
URL that I am trying to call
http://Hostname/Windchill/servlet/odata/v3/ProdMgmt/Parts('OR:wt.part.WTPart:123456')/PTC.ProdMgmt.GetPartStructure?$expand=Components($select=PartName,PartNumber;$expand=PartUse($select=FindNumber,LineNumber,Quantity,Unit);$levels=1)
Parameter that need to be passed to the URL is ('OR:wt.part.WTPart:123456'). I am doing this in C# .NET.
My C# code
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
var byteArray = Encoding.ASCII.GetBytes("abc:defg!");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
client.DefaultRequestHeaders.Add("CSRF_NONCE", a.NonceValue);
var message = await client.PostAsync("hostname/Windchill/servlet/odata/v3/ProdMgmt/Parts('OR:wt.part.WTPart:123456')/PTC.ProdMgmt.GetPartStructure?$expand=Components($select=PartName,PartNumber;$expand=PartUse($select=FindNumber,LineNumber,Quantity,Unit);$levels=1)", null);
}
Any example or sample code is much appreciated.
Related
Hello Stackoverflow community. I hope someone here can help me!!
I'm trying to integrate with the Zoopla API that requires the post request to send the following customized content type. (I've got the certificate side of things working fine).
application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json
I've tried the following approaches without any success (they all result in the following error)
System.FormatException: 'The format of value 'application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json' is invalid.'
Initial approach was to set it within the content of the RequestMessage
var request = new HttpRequestMessage()
{
RequestUri = new Uri("https://realtime-listings-api.webservices.zpg.co.uk/sandbox/v1/listing/list"),
Method = HttpMethod.Post,
Content = new StringContent(jsonBody, Encoding.UTF8, "application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json")
};
When that didn't work I tried to set it via the default headers (the client below is from the ClientFactory)
client.DefaultRequestHeaders.Add("Content-Type", "application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json");
My final attempt was to set it without validation
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json");
I've just tried something else which unfortunately didn't work
string header = "application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json";
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(header));
I am well and truly stumped!! HELP!! :-)
Content-Type is set on the content, not in DefaultRequestHeaders. You may try using TryAddWithoutValidation on the request content:
var content = new StringContent("hello");
content.Headers.ContentType = null; // zero out default content type
content.Headers.TryAddWithoutValidation("Content-Type", "application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json");
var client = new HttpClient(); // note: use IHttpClientFactory in non-example code
var response = await client.PostAsync("https://postman-echo.com/post", content);
Console.WriteLine(response.StatusCode); // OK
Console.WriteLine(await response.Content.ReadAsStringAsync());
// {"args":{},"data":{},"files":{},"form":{},"headers":{"x-forwarded-proto":"https","x-forwarded-port":"443","host":"postman-echo.com","x-amzn-trace-id":"Root=1-6345b568-22cc353761f361483f2c3157","content-length":"5","content-type":"application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json"},"json":null,"url":"https://postman-echo.com/post"}
I am trying to call a Odata service from the C# application. I have called the rest services before and consumed the responses in the C#, and trying Odata for the first time. Below is the Code I am using
using (var client = new HttpClient())
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
Uri uri = new Uri(BaseURL);
client.BaseAddress = uri;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var response = client.GetAsync(uri).Result;
var responsedata = await response.Content.ReadAsStringAsync();
I am using the same URL and the credentials in PostMan and it returns the response. But throws error i the code, is there something different we need to follow calling a Odata services.Please help with this
It is recommended to use a library to access OData. There are at least a couple of libraries that you can choose from, such as:
https://www.nuget.org/packages/Microsoft.OData.Client/ (OData v4)
https://www.nuget.org/packages/Microsoft.Data.OData/ (OData v1..3)
I try to post to rest.
This is my code:
string URL = "http://xxx.xxx.x.xx:8080/Name/NAME/";
string urlParameters = "?key=T_PAPPS&value=sofsof";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
HttpResponseMessage response = client.PostAsync(URL, new StringContent(urlParameters)).Result;
My app is WinForm application (not web).
What am I doing wrong?
Thanks for advance.
(restsharp returns same error (and there I also didn't success to change to application/x-www-form-urlencoded from application/json))
If you're using querystring parameters (ie ?key=value) you do not need to post. Try replacing your last line with:
HttpResponseMessage response = client.GetAsync(URL + urlParameters).Result;
You may also need to remove the final "/" in your URL string.
I've been having a few issues in trying to retrieve the results of a POST operation from a Web Service.
I have been using a chrome extension to test the API Services and they are working there. However I've been having problems on implementing it in code.
This is an example of usage of the chrome extension:
What I'm trying to retrieve on code, is the last part, the json array that the POST operation generates, where it says accessToken.
However, in the code that I've been using below, I've only had access to the status (200 OK) etc.
Here's a preview of the code I am using:
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url.Text);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(header.Text));
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url.Text);
request.Content = new StringContent(body.Text, Encoding.UTF8, header.Text);
client.SendAsync(request)
.ContinueWith(responseTask =>
{
MessageBox.Show(responseTask.Result.Content.Headers.ToString());
}
);
}
The Header.Text is exactly "application/json", the body.Text is body which has those various properties such as username and password (in string format) and url.Text contains the complete URL to call the Web service.
I'd like to know what I'm doing wrong with my code, and what can I do to obtain that json array that contains the accessToken
In your code you need to use ReadAsStringAsync method to convert your HttpContent object to string/json. For example:
client.SendAsync(request)
.ContinueWith(responseTask =>
{
var jsonString = responseTask.Result.Content.ReadAsStringAsync().Result;
MessageBox.Show(jsonString);
});
then you can convert you jsonString as you need.
I am writing (Attempting to write a crud application!)
I need to send a Key to the server before I can start using the service.
this.InitializeComponent();
client = new HttpClient();
client.BaseAddress = new Uri("http://dignity-network.org/api/");
I have tried
client.BaseAddress = new Uri("NO3ID81WJECJXZI83A3YYPGJKJLNEJMQ#dignity-network.org/api/")
But this does not work, what is the correct request to send authorization to a server ?
Thanks.
All depends how the server accepts and implements authorization code.
if you have to send the auth code before you start to use , you just need:
HttpContent content = HttpContent.Create(yourAuthCode, Encoding.UTF8);
HttpResponseMessage response = client.Post(new Uri ("http://dignity-network.org/api/"), content);