POST request implementation - c#

I need to implement a post request in a c# winform application of my project. Earlier to that I just have implemented get requests. I have checked that the API URI is working well (I checked it using Postman). I never implemented POST requests in the past. The get requests I implement using the following code:
WebClient n = new WebClient();
string uri = "API_URI";
string json = n.DownloadString(uri);
Now my requirement is to download json string using post method with an "apikey" with its value which I need to provide while calling the URI.
When I am using the above code, it is searching the "API_URI" in my local application directory.
Any direction, sample code and or tutorial will be much appreciated. Please help me with that.

Since you have the call tested in Postman, as a starting point use the "Code" link in PostMan to generate your call using RestSharp so that you can test it and further refine it.
https://learning.getpostman.com/docs/postman/sending-api-requests/generate-code-snippets/

you can do something like this:
WebClient client = new WebClient();
string uri = "API_URI";
string json = "{some:\"json data\"}";
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
client.Headers.Add("Authorization", "apikey");
string response = client.UploadString(uri,json);
this is the documentation https://learn.microsoft.com/en-us/dotnet/api/system.net.webclient.uploadstring?view=netframework-4.8

You can use POST method in this way
WebClient client = new WebClient();
string uri = "API_URI";
var reqparm=new NameValueCollection(); // Used for passing request perameter
reqparm.Add("some","json data");
response = Encoding.UTF8.GetString(client.UploadValues(uri, "POST", reqparm));
I hope this will help you.

Related

How to post a json and get a file stream in return in Framework 3.5?

I wrote a webservice (web api 2) and tested it successfully with the http Client. One of the Services took a json string and validated it, and then returned an appropriate download stream.
Now though I found out that I Need to write a 3.5 Framework Client for handling the whole Transfer (posting the json data and then getting the file).
As example for getting a text with web Client:
private string GetTextFromUrl(string url, JObject jsonObject)
{
WebClient webClient = new WebClient();
webClient.Headers.Add("content-type", "application/json");
return Encoding.ASCII.GetString(webClient.UploadData(url, Encoding.Default.GetBytes(jsonObject.ToString())));
}
Now though I'm a bit at a loss. From what I see with the webclient only OpenRead and DownloadFile return streams while everything else Returns a Byte Array.
Both though use only the URL and don't do any Posts (like upload data does). So I'm wondering there: Is there any possibility to post json data to a URL and receive a stream in Response with Framework 3.5? (not necessarily limited to webclient).
Edit:
To clarify as it was asked: The Client Posts a json string to the Server and receives a stream in Response. That is what I try to achieve (Client side wise).
I think you have 2 options but that is not really the problem. I think you are missing out on JSON.NET
Using WebClient
Post using webclient in .NET 3.5 is done as below by specifying headers and the "POST" method.
System.Net.WebClient client = new System.Net.WebClient();
client.Headers.Add("content-type", "application/json");//set content-type header here
string response = Encoding.ASCII.GetString(client.UploadData("http://localhost:1111/Service.svc/SignIn", "POST", Encoding.Default.GetBytes("{\"Data\": \"JSON DATA HERE\"}")));
Usually when you do the above, you should get a response from the upload method that you can assign to a variable 'response' and then use JSON.NET.
Please see this link here as well. He doesn't specify the method but uses JSON.NET and seems to work for him.
Using WebRequest
You could also try WebRequest. Please see this link for webrequest example
Hope this helps.

Programmatically login via form post and use credentials for another request

I need to login via form post in c# but then I need to use the cookies that get set in my next request to access secure data.
The initial part is pretty simple:
string URLAuth = "https://mywservice.com/login";
WebClient webClient = new WebClient();
NameValueCollection formData = new NameValueCollection();
formData["Username"] = "email#domain.com";
formData["Password"] = "password";
byte[] responseBytes = webClient.UploadValues(URLAuth, "POST", formData);
string resultAuthTicket = Encoding.UTF8.GetString(responseBytes);
webClient.Dispose();
I have this part working but how do I store and use that in an immediate next request?
I think WebClient is the wrong choice here; I would use System.Net.HttpWebRequest instead. That will give you direct access to the headers that come back in the response to your credential post, and then you can copy whatever headers (including the cookie header) onto your next HttpWebRequest to get what you're really after.

Android equivalent of WebClient in .NET

I have a fairly basic application that I wrote in C# NET some time ago and would like to rewrite it for the Android platform. It just uses an API exposed by some web software, and I can access it with just a WebClient in .NET.
WebClient myClient = new WebClient();
//Prepare a Name/Value Collection to hold the post values
NameValueCollection form = new NameValueCollection();
form.Add("username", "bob");
form.Add("password", GetMD5Hash("mypass"));
form.Add("action", "getusers");
// POST data and read response
Byte[] responseData = myClient.UploadValues("https://mysite.com/api.php", form);
string strResponse = Encoding.ASCII.GetString(responseData);
I found the WebKit (android.webkit | Android Developers) but just from quick looking that doesn't seem appropriate.
Does anyone have any sample code of how to port this over?
This could be an equivalent:
List<NameValuePair> form = new ArrayList<NameValuePair>();
form.add(new BasicNameValuePair("username", "bob");
// etc...
// Post data to the server
HttpPost httppost = new HttpPost("https://mysite.com/api.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(httppost);
To summarize HttpClient could replace your WebClient. Then you have to use either HttpPost for posting data or HttpGet for retrieving data. There are some tutorials that you can read to help you understand how you could use these classes like this one.

how to read the response from a web site?

I have a website url which gives corresponding city names by taking zip code as input parameter. Now I want to know how to read the response from the site.
This is the link I am using http://zipinfo.com/cgi-local/zipsrch.exe?zip=60680
You'll have to Use the HTTPWebRequest object to connect to the site and scrape the information from the response.
Look for html tags or class names that wrap the content you are trying to find, then use either regexes or string functions to get the required data.
Good example here:
try this (you'll need to include System.text and System.net)
WebClient client = new WebClient();
string url = "http://zipinfo.com/cgi-local/zipsrch.exe?zip=60680";
Byte[] requestedHTML;
requestedHTML = client.DownloadData(url);
UTF8Encoding objUTF8 = new UTF8Encoding();
string html = objUTF8.GetString(requestedHTML);
Response.Write(html);
The simplest way it to use the light-weight WebClient classes in System.Net namespace. The following example code will just download the entire response as a string:
using (WebClient wc = new WebClient())
{
string response = wc.DownloadString("http://zipinfo.com/cgi-local/zipsrch.exe?zip=60680");
}
However, if you require more control over the response and request process then you can use the more heavy-weight HttpWebRequest Class. For instance, you may want to deal with different status codes or headers. There's an example of using HttpWebRequest this in the article How to use HttpWebRequest and HttpWebResponse in .NET on CodeProject.
Used the WebClient Class (http://msdn.microsoft.com/en-us/library/system.net.webclient%28v=VS.100%29.aspx) to request the page and get the response as a string.
WebClient wc = new WebClient();
String s = wc.DownloadString(DestinationUrl);
You can search the response for specific HTML using String.IndexOf, SubString, etc, regular expressions, or try something like the HTML Agility Pack (http://htmlagilitypack.codeplex.com/) which was created specifically to help parse HTML.
first of all, you better find a good Web Service for this purpose.
and this is an HttpWebRequest example:
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create("http://zipinfo.com/cgi-local/zipsrch.exe?zip=60680");
httpRequest.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
Stream dataStream = httpResponse.GetResponseStream();
You need to use HttpWebRequest for receiving content and some tools for parsing html and finding what you need. One of the most popular libs for working with html in c# is HtmlAgilityPack, you can see simple example here: http://www.fairnet.com/post/2010/08/28/Html-screen-scraping-with-HtmlAgilityPack-Library.aspx
you can use a WebClient object, and an easy way to scrape the data is with xpath.

Webservice in GAE, call from a C# client

I have created a webapplication on Google App Engine that gets and sets data in datastore, using Python API and it's working fine.
Now I want to access to that data from a client application, written in C# so I was thinking of creating a webservice in GAE to provide access to the data to my app.
I have started to play a bit with ProtoRPC, and built a "hello" webservice as in the tutorial and now I want to call that webservice from my C# client application.
I have found Jayrock lib which seems to do the job; unfortunately I can't find how to make it work.
Here is my code, based on JayrockRPCClient sample :
JsonRpcClient client = new JsonRpcClient();
client.Url = "http://localhost:8081/hello";
JsonObject p = new JsonObject { { "my_name", "Joe" } };
Console.WriteLine(client.Invoke("hello.hello", p));
I always get Missing value error.
Can anybody point me to what do I do wrong ?
And as another question, what do you think of that architecture, as there a simplier way to build a webservice in GAE and call it from C#?
Note that while ProtoRPC communicates via JSON, it is not a JSON-RPC service. By using a JSON-RPC client, you are most likely sending messages in the wrong format.
You should be doing a POST to http://localhost:8081/hello.hello with a request body of {"my_name": "Joe"}. Check to make sure your client is sending requests in this format.
Using WebClient:
var uri = new Uri("http://localhost:8081/hello.hello");
var data = "{\"my_name\":\"Joe\"}";
var wc = new WebClient();
wc.Headers["Content-type"] = "application/json";
wc.Encoding = Encoding.UTF8;
var response = wc.UploadString(uri, data);
For serializing objects, you can use DataContractJsonSerializer.

Categories

Resources