I am completely new to this, I didn't even know about SOAP let alone WSDL before this, but here we go. My task is to parse some username information from a JSON API, and then send this information back via a SOAP message with WSDL.
I have the first part (for now I have the username just written in the console), I have all usernames.
Code so far:
static void Main(string[] args)
{
Uri apiUri = new Uri("https://xxxxxxxxxxxx.com/services/comex/v2/uman/users");
WebRequest webRequest = HttpWebRequest.Create(apiUri);
HttpWebRequest httpWebRequest = (HttpWebRequest)webRequest;
NetworkCredential networkCredentials = new NetworkCredential("xxxx", "xxxx");
CredentialCache myCredentialCache = new CredentialCache();
myCredentialCache.Add(apiUri, "Basic", networkCredentials);
httpWebRequest.PreAuthenticate = true;
httpWebRequest.Credentials = myCredentialCache;
WebResponse webResponse = webRequest.GetResponse();
Stream responseStream = webResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream, Encoding.Default);
string serializedJson = streamReader.ReadToEnd();
DeserializedJson deserializedJson = JsonConvert.DeserializeObject<DeserializedJson>(serializedJson);
foreach (var row in deserializedJson.result)
{
Console.WriteLine(row.usern);
}
responseStream.Close();
webResponse.Close();
}
public class Result
{
public string usern { get; set; }
}
public class DeserializedJson
{
public List<Result> result { get; set; }
}
I have the WSDL file as a separate file, which I was able to add as a service reference to my project.
I am provided with a url "https://xxxxxxxx.com/Services/Wdx/Wdx.svc/apikey" and an API-key. I am really unsure what to do with these information.
Do I send a SOAP request and include the api key in the body? What about the data package, how do I include the 4 usernames as an XML?
I'm really looking for some general information, while I'm browsing dozens of other sources about how SOAP works as well, but it's really tough to wrap my head around in such a short time (1 day)
Any advice is highly appreciated.
Related
I want to download data of this website into a json file but as I am quite new to coding with C# I cant manage to get the data. I want to get Data of https://discosweb.esoc.esa.int/api/objects the authorization via token works but I dont know how I can send a request so the server gives me a json back and I cant find a solution online. I cant give you a screenshot of the API because you have to be logged in to see it. Plz ask me for detailed information if you can help me. Thank you realy for trying.
The code I want to run is here.
class Program
{
static HttpClient client = new HttpClient();
static void Main(string[] args)
{
client.BaseAddress = new Uri("https://discosweb.esoc.esa.int");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.api+json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("my_token");
var httpRequest = (HttpWebRequest)WebRequest.Create(client.BaseAddress);
var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var streamReaderResult = streamReader.ReadToEnd();
}
Console.WriteLine("Status https://discosweb.esoc.esa.int : " + httpResponse.StatusCode);
}
}
Try this
var url = "https://discosweb.esoc.esa.int/api/objects";
var httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.Headers["Authorization"] = "Basic XXXx";
httpRequest.ContentType = "";
httpRequest.Headers["Content-Length"] = "0";
var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
Console.WriteLine(httpResponse.StatusCode);
Where XXXx is user:password in base64.
Here is a basic implementation for making that API call to get the JSON result. You will need to parse that JSON into something other than a string but I'll assume you can handle that part.
This uses System.Net.HttpClient which is the modern HTTP api provided by .NET. Its operations are async so hopefully your code is or can be written to properly await async operations.
//Someplace convenient, create a shared HttpClient to avoid
//creating and disposing for each request.
HttpClient client = new HttpClient();
string data = await GetObjects(client);
//Example implementation
public async Task<string> GetObjects(HttpClient client)
{
string url = "https://discosweb.esoc.esa.int/api/objects";
using (HttpRequestMessage msg = new HttpRequestMessage(HttpMethod.Get, url))
{
msg.Headers.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "your personal access token here");
using (var result = await client.SendAsync(msg))
{
string content = await result.Content.ReadAsStringAsync();
return content;
}
}
}
While I may be a month late, I've actually developed an SDK for this particular API.
So, if you use this SDK it's pretty simple to do what you want. You can essentially forget about handling anything HTTP related, my SDK abstracts all of that away.
For example, to fetch Sputnik's data (which has an ID of 1) you'd run.
HttpClient innerClient = new();
innerClient.BaseAddress = "https://discosweb.esoc.esa.int/api/"
innerClient.DefaultRequestHeaders.Authorization = new("bearer", yourApiKey);
DiscosClient client = new();
DiscosObject sputnik = await client.GetSingle<DiscosObject>("1");
If you're using ASP.NET, there's a set of DI extensions that can actually set it all up for you, so you can skip the first three lines.
If you do choose to use it, please let me know, as it would be nice knowing my SDK is getting some use. If you have any issues, please just reach out through the GitHub issues page and I'll try to help!
I'm working on an application to get some API experience with C#. I'm pulling data from a site involving jokes, but no matter what I try I can't seem to get the actual response.
I've gone over several different methods, this is the farthest I've gotten. I'm using the RestSharp library, and it's returning RestSharp.RestResponse. I've tried several different methods of deserializing this as that's what I believe is needed. From the API I'm using, the default response format is text/html. Any tips on extracting this to a string containing the joke itself would be most appreciated.
public void CreateJoke()
{
var client = new RestClient("https://icanhazdadjoke.com/");
client.AddDefaultHeader("user-agent", "Dadbot");
var request = new RestRequest("https://icanhazdadjoke.com/");
var response = client.Get(request);
lblJoke.Text = response.ToString();
}
Expected result: getting a string I can put into a label. Actual result: RestSharp.RestResponse.
Try instead accessing the Content property of response:
public void CreateJoke()
{
var client = new RestClient("https://icanhazdadjoke.com/");
client.AddDefaultHeader("user-agent", "Dadbot");
var request = new RestRequest("https://icanhazdadjoke.com/");
var response = client.Get(request);
lblJoke.Text = response.Content;
}
Hopefully that helps!
I guess this is what you want.
public string CreateJoke()
{
var request = (HttpWebRequest)WebRequest.Create("https://icanhazdadjoke.com/");
request.Method = "GET";
request.Accept = "text/plain";
var jokeResponse = request.GetResponse();
var joke = string.Empty;
using (var sr = new StreamReader(jokeResponse.GetResponseStream()))
{
joke = sr.ReadToEnd();
}
//Console.WriteLine(joke);
return joke;
}
Currently trying to do a Get request as part of a c# program. The request works fine on Postman as it uses a header for authorization. However I cannot get the code working for the program to use this header correctly in its Get request. I've had a good look around and tried various bits of code I've found but haven't managed to resolve it so any help would be appreciated!
public string Connect()
{
using (WebClient wc = new WebClient())
{
string URI = "myURL.com";
wc.Headers.Add("Content-Type", "text");
wc.Headers[HttpRequestHeader.Authorization] = "Bearer OEMwNjI2ODQtMTc3OC00RkIxLTgyN0YtNzEzRkE5NzY3RTc3";//this is the entry code/key
string HtmlResult = wc.DownloadString(URI);
return HtmlResult;
}
}
Above is one method inside the class.
Below is another attempt which is an extension method that gets passed the URL:
public static string GetXml(this string destinationUrl)
{
HttpWebRequest request =
(HttpWebRequest)WebRequest.Create(destinationUrl);
request.Method = "GET";
request.Headers[HttpRequestHeader.Authorization] = "Bearer
OEMwNjI2ODQtMTc3OC00RkIxLTgyN0YtNzEzRkE5NzY3RTc3";
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
string responseStr = new
StreamReader(responseStream).ReadToEnd();
return responseStr;
}
else
{
Console.Write(String.Format("{0}({1})",
response.StatusDescription, response.StatusCode));
}
return null;
}
Might I recommend the very handy RestSharp package (find it on Nuget).
It turns your current code into something like
public string Connect()
{
var client = new RestClient();
var request = new RestRequest("myURL.com", Method.GET);
request.AddParameter("Authorization", "Bearer OEMwNjI2ODQtMTc3OC00RkIxLTgyN0YtNzEzRkE5NzY3RTc3");
var response = client.Execute(request);
return response.Content;
}
It's much more succinct and easier to use (in my opinion) and thus lessens the likelihood of passing in or using incorrect methods.
If you're still having issues getting data back/connecting. Then using PostMan click Code in the upper right of PostMan and select the C# (RestSharp) option. Whatever is generated there matches exactly what PostMan is sending. Copy that over and you should get data back that matches your PostMan request.
I want to access a webpage & store the contents of the webpage into a database
this is the code I have tried for reading the contents of the webpage
public static WebClient wClient = new WebClient();
public static TextWriter textWriter;
public static String readFromLink()
{
string url = "http://www.ncedc.org/cgi-bin/catalog-search2.pl";
HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest;
webRequest.Method = "POST";
System.Net.WebClient client = new System.Net.WebClient();
byte[] data = client.DownloadData(url);
string html = System.Text.Encoding.UTF8.GetString(data);
return html;
}
public static bool WriteTextFile(String fileName, String t)
{
try
{
textWriter = new StreamWriter(fileName);
}
catch (Exception)
{
return false;
Console.WriteLine("Data Save Unsuccessful: Could Not create File");
}
try
{
textWriter.WriteLine(t);
}
catch (Exception)
{
return false;
Console.WriteLine("Data Save UnSuccessful: Could Not Save Data");
}
textWriter.Close();
return true;
Console.WriteLine("Data Save Successful");
}
static void Main(string[] args)
{
String saveFile = "E:/test.txt";
String reSultString = readFromLink();
WriteTextFile(saveFile, reSultString);
Console.ReadKey();
}
but this code gives me an o/p as- This script should be referenced with a METHOD of POST. REQUEST_METHOD=GET
please tell me how to resolve this
You are mixing HttpWebRequest with System.Net.WebClient code. They are a different. You can use WebClient.UploadValues to send a POST with WebClient. You will also need to provide some POST data:
System.Net.WebClient client = new System.Net.WebClient();
NameValueCollection postData = new NameValueCollection();
postData.Add("format","ncread");
postData.Add("mintime","2002/01/01,00:00:00");
postData.Add("minmag","3.0");
postData.Add("etype","E");
postData.Add("outputloc","web");
postData.Add("searchlimit","100000");
byte[] data = client.UploadValues(url, "POST", postData);
string html = System.Text.Encoding.UTF8.GetString(data);
You can find out what parameters to pass by inspecting the POST message in Fiddler. And yes, as commented by #Chris Pitman, use File.WriteAllText(path, html);
I'm not sure if it's a fault on your side as I get the same message just by opening the page. The page source does not contain any html so I don't think you can do webRequest.Method = "POST". Have you spoken to the administrators of the site?
The .NET framework provides a rich set of methods to access data stored on the web. First you will have to include the right namespaces:
using System.Text;
using System.Net;
using System.IO;
The HttpWebRequest object allows us to create a request to the URL, and the WebResponse allows us to read the response to the request.
We’ll use a StreamReader object to read the response into a string variable.
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URL);
myRequest.Method = "GET";
WebResponse myResponse = myRequest.GetResponse();
StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
string result = sr.ReadToEnd();
sr.Close();
myResponse.Close();
In this code sample, the URL variable should contain the URL that you want to get, and the result variable will contain the contents of the web page. You may want to add some error handling as well for a real application.
As far as I see, the URL you're requesting is a perl script. I think it demands POST to get search arguments and therefore delivers search results.
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