I have been coding a application in c#, which data is send through get function
Its like this
Http://www.myweb.com/co.php?a=10&b=20
I am new to c# web programming, so i was wondering how can send the same data through post function. Because if i use $_POST in the php file it dont get the values, i researched a bit and found that POST function takes data in the body rather then in URL.
I just to convert the procedure from GET TO POST. Any help will be greatly appreciated.
You can use HttpWebRequest, setting the Method and ContentType properties appropriately:
var request = (HttpWebRequest)WebRequest.Create("http://www.myweb.com/co.php");
// your choice of encoding, I just picked ASCII here
var body = System.Text.Encoding.ASCII.GetBytes("a=10&b=20");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = body.Length;
using (var stream = request.GetRequestStream()) {
stream.Write(body, 0, body.Length);
}
If you're targeting .NET 4.5 I'd suggest using HttpClient if not then I'd go with WebClient:
WebClient webClient = new WebClient();
NameValueCollection values = new NameValueCollection();
values.Add("FirstName", "John");
values.Add("LastName", "Smith");
values.Add("Age", "46");
webClient.UploadValues("http://example.com/", values);
Related
I have an api
http://cbastest.cadvilpos.com/module/posmodule/customapi
with parameters
{
"action":4,
"device_token": "3e8ea119a90ee6d2",
"key":"9475962085b3a1b8c475d52.95782804",
"shop":1,
"language":1
}
This is working fine in postman. But when I try to connect from c# project its showing an error {"success":0,"error":"Missing the action parameter."}. Please give a working C# code to get the json result.
The code I tried:
var request = (HttpWebRequest)WebRequest.Create("http://cbastest.cadvilpos.com/module/posmodule/customapi");
var postData = "{ 'action':'4', 'device_token':'3e8ea119a90ee6d2','key':'9475962085b3a1b8c475d52.95782804','shop':'1','language':'1'}";
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response2 = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response2.GetResponseStream()).ReadToEnd();
You don't need to use a raw HttpWebRequest object to make an HTTP call. HttpClient was introduced in 2012 to allow easy asynchronous HTTP calls.
You could do something as simple as :
var content=new StringContent(postData,Encoding.UTF8, "application/json");
HttpResponseMessage response=await httpClient.PostAsync(url,content);
//Now process the response
if (response.IsSuccessCode)
{
var body=await response.Content.ReadAsStringAsync();
var responseDTO=JsonConvert.DeserializeObject<MyDTO>(body);
}
Instead of building a JSON string by hand you could use a strongly typed class or an anonymous object and serialize it to JSON with JSON.NET :
var data=new {
action=4,
device_token="3e8ea119a90ee6d2",
key = "9475962085b3a1b8c475d52.95782804",
shop=1,
language=1
};
var postData=JsonConvert.SerializeObject(data);
var content=new StringContent(postData,Encoding.UTF8, "application/json");
var response=await httpClient.PostAsync(url,content);
...
You can read a response body in one go as a string, using ReadAsStringAsync or you can get the response stream with ReadAsStreamAsync. You could copy the response data directly to another stream, eg a file or memory stream with HttpContent.CopyToAsync
Check Call a Web API from a .NET Client for more examples. Despite the title, the examples work to call any HTTP/REST API.
The Microsoft.AspNet.WebApi.Client package mentioned in that article is another thing that applies to any call, not just calls to ASP.NET Web API. The extension method PostAsJsonAsync for example, combines serializing and posting a request to a url. Using it, posting the action DTO could be reduced to a single line:
var data=new {
action=4,
device_token="3e8ea119a90ee6d2",
key = "9475962085b3a1b8c475d52.95782804",
shop=1,
language=1
};
var response=await httpClient.PostAsJsonAsync(url,data);
There is a button in Postman that will generate code for the currently defined request. The link is here:
And this is what the code looks like. You'll need to pull in RestSharp from Nuget
I have a Windows app written in C#. This app will be deployed to my user's desktops. It will interact with a back-end that has already been created. The back-end is written in ASP.NET MVC 3. It exposes a number of GET and POST operations as shown here:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetItem(string id, string caller)
{
// Do stuff
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SaveItem(string p1, string p2, string p3)
{
// Do stuff
}
The web developers on my team are successfully interacting with these operations via JQuery. So I know they work. But I need to figure out how to interact with them from my Windows C# app. I was using the WebClient, but ran into some performance problems so I was consulted to use the WebRequest object. In an honest effort to attempt this, I tried the following:
WebRequest request = HttpWebRequest.Create("http://www.myapp.com/actions/AddItem");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.BeginGetResponse(new AsyncCallback(AddItem_Completed), request);
My problem is, I'm not sure how to actually send the data (the parameter values) back to my endpoints. How do I send the parameter values back to my GET and POST operations? Can someone give me some help? Thank you!
One way is to write the input to request stream. You need to serialize input to byte array
Please see below sample code
string requestXml = "someinputxml";
byte[] bytes = Encoding.UTF8.GetBytes(requestXml);
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentLength = bytes.Length;
request.ContentType = "application/xml";
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
using (var response = (HttpWebResponse)request.GetResponse())
{
statusCode = response.StatusCode;
if (statusCode == HttpStatusCode.OK)
{
responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
}
}
Well, with WebClient the simplest example would be something like this:
NameValueCollection postData = new NameValueCollection();
postData["field-name-one"] = "value-one";
postData["field-name-two"] = "value-two";
WebClient client = new WebClient();
byte[] responsedata = webClient.UploadValues("http://example.com/postform", "POST", postData);
Have you tried this?
So basically I have some french text and want to traduce it in english using c#.
I'm using google translate api, which was working fine until i had a text.length > 1000 .... then I realized that I must use POST method.
Since I use the post method, it returns me 404.
btw i know the api is deprecated, I though it would be cool anyways but I'm starting to realize maybe i should use bing ?
string fromLanguage = "fr";
string toLanguage = "en";
String apiKey = "AIzasdfasdfJvWKNioZwLg-3kyYsm4_dao";
String apiUrl = "https://www.googleapis.com/language/translate/v2";
string tmpTranslatedContent = Translate(apiUrl, "salut la planete", apiKey, fromLanguage, toLanguage);
public string Translate(string url, string text, string key, string fromLanguage, string toLanguage)
{
PostSubmitter post = new PostSubmitter();
post.Url = url;
post.PostItems.Add("key", key);
post.PostItems.Add("source", fromLanguage);
post.PostItems.Add("target", toLanguage);
post.PostItems.Add("q", text);
post.Type = PostSubmitter.PostTypeEnum.Post;
string result = post.Post();
return result;
}
PostSubmitter is a class i found when searching google
Comments on the site are saying it works.....
the main part of the class looks like this
HttpWebRequest request=null;
if (m_type==PostTypeEnum.Post)
{
Uri uri = new Uri(url);
request = (HttpWebRequest) WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
using(Stream writeStream = request.GetRequestStream())
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(postData);
writeStream.Write(bytes, 0, bytes.Length);
}
thanks.
This is a little old, but I just ran into a similar problem but with PHP instead of C# and the fix should be quite similar.
Basically, even though you are using POST, you still need to tell Google that from a REST point of view you are actually doing a GET. This can be done with the X-HTTP-Method-Override header, setting it to be: X-HTTP-Method-Override: GET
Google tells me that as ASP.NET MVC, version 2, there is a method HttpHelper.HttpMethodOverride that will allow you to do this.
According to the Google Translate API however, text is still limited to 5k even when posting.
I need to use StreamSend API to send email, here is
StreamSend API Reference
I am making web request as post to following URL with proper credentials
https://app.streamsend.com/audiences/2/blasts.xml
StringBuilder sb = new StringBuilder();
sb.Append("https://app.streamsend.com/audiences/2/blasts.xml");
Uri uri = new Uri(sb.ToString());
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
request.ContentType = "application/xml";
StringBuilder strMail= new StringBuilder();
strMail.Append("<blast> ALL from api..... </blast>");
byte[] data = Encoding.ASCII.GetBytes(strMail.ToString());
Stream input = request.GetRequestStream();
input.Write(data, 0, data.Length);
input.Close();
HttpWebResponse nsResponse = (HttpWebResponse)request.GetResponse();
i am having err# 422 or 500. i would appreciate any help.
A couple of things. First, it looks like you're trying to do a POST request (you're sending data in the request stream). If you really want a POST request, you have to set request.Method = "POST";
Also, if you want an XML response, you need to set the Accept header. According to the documentation you listed, you need: request.Accept = "application/xml";
And you need to add your login id to the request, as well. I'm not sure how that's done. Perhaps in the request.Credentials property like this:
request.Credentials = new NetworkCredential("login_id", "your_key_here");
Finally, there's no reason to use StringBuilder if all you're doing is assigning strings. You can write, for example:
string urlString = "https://app.streamsend.com/audiences/2/blasts.xml"
Uri uri = new Uri(urlString);
or
byte[] data = Encoding.ASCII.GetBytes("<blast> ALL from api..... </blast>");
This code is for an outlook plugin. We're trying to POST to a page and are getting this error:
The remote server returned an error: (422) Unprocessable Entity.
The C# code is here:
webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
Byte[] postData = asciiEncoding.GetBytes("email=e2#email.com&password=hunter2");
char[] resultHTML = asciiEncoding.GetChars(webClient.UploadData("http://url", "POST", postData));
string convertedResultHTML = new string(resultHTML);
Any idea what could be causing this?
POST data must be encoded prior to be sent out on the wire as ASCII, if you are sending character not in the ASCII range. You should try something like:
Byte[] postData = asciiEncoding.GetBytes(HttpUtility.UrlEncode("email=e2#email.com&password=hunter2"));
Because of its limited functionality, I avoid using WebClient and use WebRequest instead. The code below:
does not expect an HTTP 100 status code to be returned,
creates a CookieContainer to store any cookies we pick up,
sets the Content Length header, and
UrlEncodes each value in the post data.
Give the following a try and see if it works for you.
System.Net.ServicePointManager.Expect100Continue = false;
System.Net.CookieContainer cookies = new System.Net.CookieContainer();
// this first request just ensures we have a session cookie, if one exists
System.Net.WebRequest req = System.Net.WebRequest.Create("http://localhost/test.aspx");
((System.Net.HttpWebRequest)req).CookieContainer = cookies;
req.GetResponse().Close();
// this request submits the data to the server
req = System.Net.WebRequest.Create("http://localhost/test.aspx");
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
((System.Net.HttpWebRequest)req).CookieContainer = cookies;
string parms = string.Format("email={0}&password={1}",
System.Web.HttpUtility.UrlEncode("e2#email.com"),
System.Web.HttpUtility.UrlEncode("hunter2"));
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(parms);
req.ContentLength = bytes.Length;
// perform the POST
using (System.IO.Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
// read the response
string response;
using (System.Net.WebResponse resp = req.GetResponse())
{
if (resp == null) return;
using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
{
response = sr.ReadToEnd().Trim();
}
}
// the variable response holds the results of the request...
Credits: Hanselman, Simon (SO Question)
This is the RoR application telling you that you have not formed a request that it can handle; the destination script exists (otherwise you'd see a 404), the request is being handled (otherwise you'd get a 400 error) and it's been encoded correctly (or you'd get a 415 error) but the actual instruction can't be carried out.
Looking at it, you seem to be loading some email information. The RoR application could be telling you that the username and password is wrong, or that the user doesn't exist, or something else. It's up to the RoR application itself.
I think the code itself is good; it's just that the app at the other end isn't happy about doing what you ask it. Are you missing something else in the request information, like a command? (eg command=getnetemails&email=e2#email.com&password=hunter2) Are you sure the email/password combination you are passing is good?
see here for more on the 422 error.
Add the below line above your code.
System.Net.ServicePointManager.Expect100Continue = false;
Are you trying to access an authentication required page?
it was solved by returning xml instead of just unstructured text on the RoR side