SOAP Request with HttpClient - c#

I'am trying to reach a SOAP API using the HttpClient object. I've searched everywhere but most of the people are using the HttpWebRequest object which is not supported by the DNX Core framework.
Does anyone have a working example of a SOAP request using the HttpClient object?
This image represents a simple request from this API (NuSOAP PHP):
Thank you!
EDIT :
So I was able to call the API with the following code:
Uri uri = new Uri("http://localhost/teek_api/service.php");
HttpClient hc = new HttpClient();
hc.DefaultRequestHeaders.Add("SOAPAction", "http://localhost/teek_api/service.php/ping");
var content = new StringContent("text/xml; charset=utf-8");
using (HttpResponseMessage response = await hc.PostAsync(uri, content))
{
var soapResponse = await response.Content.ReadAsStringAsync();
string value = await response.Content.ReadAsStringAsync();
return value;
}

Related

could not create ssl/tls secure channel when call an API

i'm get this code from a curl-to-c# convertor site
curl is working but in this code i get error: could not create ssl/tls secure channel
using System.Net.Http.Headers;
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://www.alsatpardakht.com/IPGAPI/Api22/send.php");
request.Headers.Add("Cookie", "PHPSESSID=td3qg4c25oo5jrft5m0sd48om1");
request.Content = new StringContent("Amount=20000&ApiKey=YOUR APIKEY&Tashim=%5B%5D&RedirectAddressPage=www.test.com&PayId=111");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
HttpResponseMessage response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
if anyone to try real, i can give him the api-key to test it
this api call works in other lang but not in c#

HttpClientFactory returns results of previous request

I have an ASP.NET Core Web API service built using .NET 6 that makes http requests using C# HttpClientFactory to external services.
The issue I am facing is that the second request with different arguments returns same result as for the previous request.
I tried clearing default headers at the start of every request no luck.
What worked for me:
RestSharp: https://restsharp.dev/
Using new HttpClient() instance instead of httpClientFactory.CreateClient()
I would like to make it work with httpClientFactory as this is the recommended way. Any thoughts why much appreciated.
// Each request has different access token but same body
public async Task<MyResponse> GetXyz(object requestBody, string accessToken)
{
var uri = "...";
return await this.httpClientFactory.CreateClient("GetXyz").PostAsync<MyResponse>(uri, requestBody, GetHeaders(accessToken));
}
private static IList<(string, string)> GetHeaders(string accessToken)
{
var headers = new List<(string, string)>
{
(HeaderNames.Accept, "application/json"),
};
if (!string.IsNullOrWhiteSpace(accessToken))
{
headers.Add((HeaderNames.Authorization, "Bearer " + accessToken));
}
return headers;
}
public static async Task<T> PostAsync<T>(this HttpClient httpClient, string uri, object data, IList<(string, string)> headers = null)
where T : class
{
// httpClient.DefaultRequestHeaders.Clear();
var body = data.Serialise(); // convert to JSON string
using (var request = new HttpRequestMessage(HttpMethod.Post, uri))
{
request.AddRequestHeaders(headers);
request.Content = new StringContent(body, Encoding.UTF8, "application/json");
using (var httpResponse = await httpClient.SendAsync(request))
{
var jsonResponse = await httpResponse.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<T>(jsonResponse);
}
}
}
EDIT 2: NETWORK TRAFFIC DIFF
Using Fiddler Classic with basic client httpclientfactory.CreateClient() here are the diffs between 2 requests headers that suffer from the issue:

How to serialize-deserialize object using HTTP GetAsync method?

After I upgraded the framework of web app from 4.0 to 4.6 I found that there is no more ReadAsAsync() method in HTTP protocol library, instead of ReadAsAsync() there is GetAsync(). I need to serialize my custom object using GetAsync().
The code using ReadAsAsync():
CustomResponse customResponse = client.ReadAsAsync("api/xxx", new StringContent(new JavaScriptSerializer().Serialize(request), Encoding.UTF8, "application/json")).Result;
Another example based on ReadAsAsync()
CustomResponse customResponse = await Response.Content.ReadAsAsync<CustomResponse>();
How to achieve same goal using GetAsync() method ?
You can use it this way:
(you might want to run it on another thread to avoid waiting for response)
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(page))
{
using (HttpContent content = response.Content)
{
string contentString = await content.ReadAsStringAsync();
var myParsedObject = (MyObject)(new JavaScriptSerializer()).Deserialize(contentString ,typeof(MyObject));
}
}
}

Adding authentication header to HttpClient

I'm trying to access an API, but all the documentation is in PHP and I'm not very familiar with PHP. I am having trouble authenticating to the API. The documentation is here.
Here is what I have so far
var webAddress = "https://xboxapi.com/v2/latest-xbox360-games";
var httpResponse = (new HttpClient().GetAsync(webAddress)).Result;
httpResponse.EnsureSuccessStatusCode();
var jsonResponse = httpResponse.Content.ReadAsStringAsync().Result;
I'm just not sure how to add the authentication header that they are using in PHP.
Any help would be appreciated.
To add a custom header (in this case X-AUTH), you need to send a custom HttpRequestMessage. For example:
var webAddress = "https://xboxapi.com/v2/latest-xbox360-games";
HttpClient client = new HttpClient();
HttpRequestMessage msg = new HttpRequestMessage(HttpMethod.Get, webAddress);
msg.Headers.Add('X-AUTH', 'your-auth-key-here');
HttpResponseMessage response = await client.SendAsync(msg);

HTTP POST Though C#

I want to code an auto bot for an online game (tribalwars.net). I'm learning C# in school, but haven't covered networking yet.
Is it possible to make HTTP POSTs though C#? Can anyone provide an example?
Trivial with System.Net.WebClient:
using(WebClient client = new WebClient()) {
string responseString = client.UploadString(address, requestString);
}
There is also:
UploadData - binary (byte[])
UploadFile - from a file
UploadValues - name/value pairs (like a form)
You can use System.Net.HttpWebRequest:
Request
HttpWebRequest request= (HttpWebRequest)WebRequest.Create(url);
request.ContentType="application/x-www-form-urlencoded";
request.Method = "POST";
request.KeepAlive = true;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(BytePost,0,BytePost.Length);
requestStream.Close();
}
Response
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using(StreamReader sr = new StreamReader(response.GetResponseStream()))
{
responseString = sr.ReadToEnd();
}
Here's a good example. You want to use the WebRequest class in C#, which will make this easy.
I understand this is old question, but posting this for someone looking for quick example on how to send Http Post request with json body in latest .NET (Core 5), using HttpClient (part of System.Net.Http namespace). Example:
//Initialise httpClient, preferably static in some common or util class.
public class Common
{
public static HttpClient HttpClient => new HttpClient
{
BaseAddress = new Uri("https://example.com")
};
}
public class User
{
//Function, where you want to post data to api
public void CreateUser(User user)
{
try
{
//Set path to api
var apiUrl = "/api/users";
//Initialize Json body to be sent with request. Import namespaces Newtonsoft.Json and Newtonsoft.Json.Linq, to use JsonConvert and JObject.
var jObj = JObject.Parse(JsonConvert.SerializeObject(user));
var jsonBody = new StringContent(jObj.ToString(), Encoding.UTF8, "application/json");
//Initialize the http request message, and attach json body to it
var request = new HttpRequestMessage(HttpMethod.Post, apiUrl)
{
Content = jsonBody
};
// If you want to send headers like auth token, keys, etc then attach it to request header
var apiKey = "qwerty";
request.Headers.Add("api-key", apiKey);
//Get the response
using var response = Common.HttpClient.Send(request);
//EnsureSuccessStatusCode() checks if response is successful, else will throw an exception
response.EnsureSuccessStatusCode();
}
catch (System.Exception ex)
{
//handle exception
}
}
}
Why is HttpClient static or recommended to be instantiated once per application:
HttpClient is intended to be instantiated once and re-used throughout
the life of an application. Instantiating an HttpClient class for
every request will exhaust the number of sockets available under heavy
loads. This will result in SocketException errors.
HttpClient class has async methods too. More info on HttpClient class: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-5.0

Categories