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.
Related
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.
I have my telegram application with app's api_id and app's api_hash.
I used TLSharp library for implementing my own things. But now I need to use this https://core.telegram.org/method/auth.checkPhone telegram api method, but it's not implemented in TLSharp library!
I don't mind doing it all manually, but I don't know how!
I know how you send post requests in C#, example:
var response = await client.PostAsync("http://www.example.com/index", content);
but in this specific case I don't. Because I don't know:
1) what link should I use for sending post requests? I couldn't find it on the telegram's website.
2) what content should I pass there? Should it be just "(auth.checkPhone "+380666454343")" or maybe the whole "(auth.checkPhone "+380666454343")=(auth.checkedPhonephone_registered:(boolFalse)phone_invited:(boolFalse))" ?
So, How do I sent this post request to the telegram api? (NOT telegram bot api!)
Try to use System.Net.Http like in this example (auth request to the server):
var user = new { login = "your login", password = "your pass" };
string json = JsonConvert.SerializeObject(user);
HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage();
request.RequestUri = new Uri("server route link"); // can be like https://a100.technovik.ru:1000/api/auth/authenticate
request.Method = HttpMethod.Post;
request.Content = content;
HttpResponseMessage response = await client.SendAsync(request);
responseText.Text = await response.Content.ReadAsStringAsync();
I think based on a brief look, that it would be more along the lines of your second example, e.g.:
var phonenumber = "0123456789";
var content =
$#"(auth.checkPhone ""{phonenumber}"")"+
"=(auth.checkedPhone phone_registered: (boolFalse) phone_invited:(boolFalse))";
var result = DoHttpPost("http://some.example.com/api/etc", content);
(note: I've not listed the actual mechanics of an HTTP Request here, as that is covered in plenty of detail elsewhere - not least in the other current answer supplied to you; DoHttpPost() is not a real method and exists here only as a placeholder for this process)
And since the payload of this appears to indicate the exact function and parameters required, that you'd just send it to the base api endpoint you use for everything, but I can't say for sure...
I do note they do appear to have links to source code for various apps on the site though, so perhaps you'd be better off looking there?
I'm trying to do a very simple HTTP request on a URL in order to use the returned data. Everything I've done before and everything I'm reading on MSDN indicates that this should work:
string url = "http://www.abettergeek.com/misc/hovservice.php";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
However, GetResponse() apparently doesn't exist for HttpWebRequest, even though it seems like it should.
What am I doing wrong here?
Edit:
I figured out how to use HttpClient correctly. I was trying to assign the result of the HttpClient stream to a variable, which wasn't working the way I wanted it to.
I ended up using the following:
Uri north = new Uri("http://www.abettergeek.com/misc/hovservice.php");
HttpClient northc = new HttpClient();
string northr = await northc.GetStringAsync(north);
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.
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.