Simple Restclient POST issue - c#

Been searching for hours for an answer and cant seem to find anything. I am trying to update from a Windows forms project to a Web Service using Rest client. I have successfully managed to "GET" into a Datagridview, but i am having trouble using "POST". Here is a snippet of the code i am trying to use (Generate License is a method that writes it to a xml document and returns the stream):
EDIT: The HttpResponse is giving me this error:
<?xml version="1.0"?>
<Licenses_table><Licenses><ErrorCode>HY000</ErrorCode><DriverCode>1364</DriverCode><Message>Field 'Code' doesn't have a default value</Message></Licenses></Licenses_table>
string Url = "http://localhost:8810/ReplicationService.php/Licenses/";
byte[] dataByte = GenerateLicense(Code, Version1, Name);
HttpWebRequest POSTrequest = (HttpWebRequest)WebRequest.Create(Url);
POSTrequest.Method = "POST";
POSTrequest.ContentType = "text/xml";
POSTrequest.KeepAlive = false;
POSTrequest.Timeout = 5000;
POSTrequest.ContentLength = dataByte.Length;
Stream POSTstream = POSTrequest.GetRequestStream();
POSTstream.Write(dataByte, 0, dataByte.Length);

Is that the whole code you are showing? I dont see where you are closing the request stream, and then calling GetResponse() on the WebRequest?

Related

Issues passing an Xml file to a method in console application

I am working on a c# console application where I am making a Http Post request to a web api by using xml file and I'm kind of new to XML and web services but I figured out the following code for the request but failed to pass xml data to the method
static void Main(string[] args)
{
string desturl=#"https://xyz.abcgroup.com/abcapi/";
Program p = new Program();
System.Console.WriteLine(p.WebRequestPostData(desturl, #"C:\Applications\TestService\FixmlSub.xml"));
}
public string WebRequestPostData(string url, string postData)
{
System.Net.WebRequest req = System.Net.WebRequest.Create(url);
req.ContentType = "text/xml";
req.Method = "POST";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(postData);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
using (System.Net.WebResponse resp = req.GetResponse())
{
if (resp == null) return null;
using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
{
return sr.ReadToEnd().Trim();
}
}
}
For obvious reasons the above code throws 404 error as I think I am not passing the xml data properly
May I know how I can fix this?
You're not posting xml, your posting the string C:\Applications\TestService\FixmlSub.xml
Change your method call from:
System.Console.WriteLine(p.WebRequestPostData(desturl, #"C:\Applications\TestService\FixmlSub.xml"));
to
var xml = XElement.Load(#"C:\Applications\TestService\FixmlSub.xml");
System.Console.WriteLine(p.WebRequestPostData(desturl, xml.ToString(SaveOptions.DisableFormatting));
If you are trying to learn post / receive, go for it. But there are open source libraries that are already well tested to use if you want to use them.
The non-free version of Servicestack.
And their older free-version. I think the older free version is great. I've never tried the newer one. You deal with objects, like say an Employee and pass that to the library and it does the translation to xml or whatever the web-service wants.
You can post whole strings if you want. They have great extension methods to help you with that too.

Looks like only a part of the API call is anwered in Ahsay

Some time ago I started to use the api call system of Ahsay and wasn't that difficult to understand.
In the webbrowser the API call works, but when I try to use C# only a part seems to get to Ahsay?
I'm using this code of CodeProject to do the API call:
http://www.codeproject.com/Tips/497123/How-to-make-REST-requests-with-Csharp
In this code I send as API call:
{SysUser: system, SysPwd: system, LoginName: test, Owner: , Password: test}
and get as error code:
<err>[Error] Parameter LoginName is null/empty!</err>
If I sent the same requist as an URL like:
http://SERVERIP/obs/api/AuthUser.do?SysUser=system&SysPwd=system&LoginName=test&Password=test`
it gives as error code: <err>[Error] The password must be at least 6 characters in length!</err>
Can somebody explain to me why the LoginName isn't send or received in the C# code?
If someone encounters the same problem, here is the code I's using:
public void API_HTTP()
{
string url = "http://URL";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
StreamReader reader = new StreamReader(resStream);
String output = reader.ReadToEnd();
}

Simple Get Post in Asp.net as like in PHP

I ran into a problem. I am .Net Developer and don't know about php, I am working on a CRM which has an API. My Client says it should be simple page should work with simple post. now i don't understand how i can do a simple Post in .Net. I have created an asp.net WebForm. All is working well. The only thing that i have problem with is that i have to return a list of parameters to response. I am using
Response.Write("100 - Click Recorded Successfully.");
but this return a full html Document with the parameter string at the top of the document. I saw one php Api which return only the prameter string like this with out HTML Document:
response=1
&responsetext=SUCCESS
&authcode=123456
&transactionid=2154229522
&avsresponse=N
&cvvresponse=N
&orderid=3592
&type=sale
&response_code=100
can some one suggest me any better way how i can do this. I found many article that explains how to do a simple Get Post in .Net but none of these solved my problem.
Update:
this is the code that i am using from another application to call the page and get response stream
string result = "";
WebRequest objRequest = WebRequest.Create(url + query);
objRequest.Method = "POST";
objRequest.ContentLength = 0;
objRequest.Headers.Add("x-ms-version", "2012-08-01");
objRequest.ContentType = "application/xml";
WebResponse objResponse = objRequest.GetResponse();
using (StreamReader sr =
new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
// Close and clean up the StreamReader
sr.Close();
}
string temp = result;
where url + query is the address to my page. The result shows this code http://screencast.com/t/eKn4cckXc. I want to get the header line only, that is "100 - Click Recorded Successfully."
You have two options. First is to clear whatever response was already generated on the page, write the text, and then end the response so that nothing else added:
Response.Clear();
Response.ClearHeaders();
Response.AddHeader("Content-Type", "text/plain");
Response.Write(Request.Url.Query);
Response.End();
That is if you want to process it on the Page. However a better approach would be to implement Http Handler, in which case all you need to do is:
public void ProcessRequest
{
Response.AddHeader("Content-Type", "text/plain");
Response.Write(Request.Url.Query);
}

C# api responce and request

I currently have the code
try
{
string url = "http://myanimelist.net/api/animelist/update/" + "6.xml";
WebRequest request = WebRequest.Create(url);
request.ContentType = "xml/text";
request.Method = "POST";
request.Credentials = new NetworkCredential("username", "password");
byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes("<episode>4</episode>");
Stream reqstr = request.GetRequestStream();
reqstr.Write(buffer, 0, buffer.Length);
reqstr.Close();
MessageBox.Show("Updated");
}
catch (Exception s)
{
MessageBox.Show(s.Message);
}
I am trying do send data to myanimelist.net
The code they have written for is this
URL: http://myanimelist.net/api/animelist/update/id.xml
Formats: xml
HTTP Method(s): POST
Requires Authentication:true
Parameters:
id. Required. The id of the anime to update.
Example: http://myanimelist.net/api/animelist/update/21.xml
data. Required. A parameter specified as 'data' must be passed. It must contain anime values in XML format.
Response: 'Updated' or detailed error message.
The usage code example the have stated is this, does anyone know how to do this in c# or what was wrong with my original code?
Usage Examples:
CURL: curl -u user:password -d data="XML" http://myanimelist.net/api/animelist/update/21.xml
edit: When i lauch myanimelist.net it shows that it has not been updated, i am sure that my username and password credentials are correct
Edit 2 : I have now added a response which comes up with the error
"The remote server returned an error: (501) Not Implemented."
You're not actually performing the request, so once you're done writing to the request stream itself, perform the actual web request:
string result;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
}
Also, the content type should be text/xml or application/xml - the API may be complaining about that. Read the documentation for their API carefully and ensure what you're sending is correct.

Problems consuming WebService in .Net (ReCaptcha)

I am having difficulty in consuming the reCaptcha Web Service using C#/.Net 3.5. Although I think the problem is with consuming web services in general.
String validate = String.Format("http://api-verify.recaptcha.net/verify?privatekey={0}&remoteip={1}&challenge={2}&response={3}", PrivateKey, UserIP, Challenge, Response);
WebClient serviceRequest = new WebClient();
serviceRequest.Headers.Add("ContentType","application/x-www-form-urlencoded")
String response = serviceRequest.DownloadString(new Uri(validate ));
It keeps telling me that the error is: nverify-params-incorrect. Which means:
The parameters to /verify were incorrect, make sure you are passing all the required parameters.
But it's correct. I am using the private key, the IP address (locally) is 127.0.0.1, and the challenge and response seem fine. However the error keeps occurring.
I am pretty sure this is a issue with how I am requesting the service as this is the first time I have actually used webservices and .Net.
I also tried this as it ensures the data is posted:
String queryString = String.Format("privatekey={0}&remoteip={1}&challenge={2}&response={3}",PrivateKey, UserIP, Challenge, Response);
String Validate = "http://api-verify.recaptcha.net/verify" + queryString;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(Validate));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = Validate.Length;
**HttpWebResponse captchaResponse = (HttpWebResponse)request.GetResponse();**
String response;
using (StreamReader reader = new StreamReader(captchaResponse.GetResponseStream()))
response = reader.ReadToEnd();
Seems to stall at the point where I get response.
Any advice?
Thanks in advance
Haven't worked with the recaptcha service previously, but I have two troubleshooting recommendations:
Use Fiddler or Firebug and watch what you're sending outbound. Verifying your parameters would help you with basic troubleshooting, i.e. invalid characters, etc.
The Recaptcha Wiki has an entry about dealing with development on Vista. It doesn't have to be limited to Vista, though; if you're system can handle IPv6, then your browser could be communicating in that format as a default. It appears as if Recaptcha deals with IPv4. Having Fiddler/Firebug working would tell you about those other parameters that could be causing you grief.
This may not help solve your problem but it might provide you with better troubleshooting info.
So got this working, for some reason I needed to write the request to a stream like so:
//Write data to request stream
using (Stream requestSteam = request.GetRequestStream())
requestSteam.Write(byteData, 0, byteData.Length);
Could anyone explain why this works. I didn't think I would need to do this, don't completely understand what's happening behind the scenes..
Damien's answer is correct of course, but just to be clear about the order of things (I was a little confused) and to have a complete code sample...
var uri = new Uri("http://api-verify.recaptcha.net/verify");
var queryString = string.Format(
"privatekey={0}&remoteip={1}&challenge={2}&response={3}",
privateKey,
userIP,
challenge,
response);
var request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = WebRequestMethods.Http.Post;
request.ContentLength = queryString.Length;
request.ContentType = "application/x-www-form-urlencoded";
using (var writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(queryString);
}
string result;
using (var webResponse = (HttpWebResponse)request.GetResponse())
{
var reader = new StreamReader(webResponse.GetResponseStream());
result = reader.ReadToEnd();
}
There's a slight difference in that I'm writing the post variables to the request, but the core of it is the same.

Categories

Resources