Convert C# HttpWebRequest in PHP cURL Request - c#

I'm new with cURL, I succeeded with my first request but now I'm stuck. I have the right request in C# but I don't know how to convert the second in cURL PHP.
Here is the HttpWebRequest:
var request = (HttpWebRequest)WebRequest.Create(new Uri("https://www.google.fr"));
request.Method = HttpMethod.Get;
request.Headers["X-343-Authorization-WLID"] = "v1=" + accessToken;
request.Accept = "application/json";
accessToken is a string variable of course.

Here are the three base curl_setopt calls you'll need to make.
curl_setopt($ch,CURLOPT_URL,"$website");
curl_setopt($ch,CURLOPT_ENCODING, 'application/json');
curl_setopt($ch,CURLOPT_HTTPHEADER, array("X-343-Authorization-WLID:v1=$accesstoken"));
You might want to add follow_location and return_transfer, but I don't know exactly what you're doing. Both of those options are listed in the curl_setopt documentation.
That page should have enough examples to get you going.

Related

POST or GET method?

We have a service provider that allows us to connect to his payment page for payments, however the code he uses is php but we would like to do it in asp.net.
Problem is I don't really understand what the method should be, POST or GET, basically we need to redirect to the client with underlying parameters(not query strings) and then our current page that calls the request must be redirected to the client page with the parameters as well.
I do get the response witch is basically markup, but that's not what I want, I want it to redirect to the payment page, can someone please tell me what I do wrong.Thanks
Here is my code I use for the POST Method:
string query = string.Format("description={0}&amount={1}&merchantIdent={2}&email={3}&transaction={4}&merchantKey={5}",
description.ToString(), amount.ToString(), merchantIdent.ToString(), email.ToString(), id.ToString(), merchantKey.ToString());
// Create the request back
string url = "https://www.webcash.co.za/pay";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.AllowAutoRedirect = true;
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = query.Length;
req.AllowAutoRedirect = true;
StreamWriter stOut = new StreamWriter(req.GetRequestStream(),System.Text.Encoding.ASCII);
stOut.Write(query);
stOut.Close();
// Do the request
StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());
string response = stIn.ReadToEnd();
stIn.Close();
Not sure I totally understand your question, but as your title goes, here is the difference between POST and GET:
The GET method passes variables through the url. This can be practical or impractical (for instance if you plan to pass sensitive material to another page)
The POST method does not pass variables through the url, it passes the variables behind the scenes.
You'll need to decide which better fits your situation.
Normally GETs are idempotent (meaning they don't change data). Use a GET if you want to be able to issue a request and not change anything. Use a POST if you're performing some sort of update/processing/etc.

HttpWebRequest with GET: 401 unauthorized

I found some problem with httpWebRequest, I've read all the same issues on other forums, but answers don't seem to work. My code:
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse resp;
wr.ContentType = "text/html; charset=UTF-8";
wr.Method = "GET";
wr.Credentials = new NetworkCredential("user", "password");
resp = (HttpWebResponse)wr.GetResponse();
The remote server returned an error: (401) Unauthorized.
Response says there's no auth token in cookies. I can receieve this token using my auth request with POST method. I even tried to put it to CookieContainer by "new Cookie ("authToken",token_value)". But the result is the same - error 401. Does anybody know the solution?
Thanx.
I use Zimbra web server, have an access to control it. .NET 4.0. My url is the path to .eml file I need to download. To specify the file I need to add some GET parameters: id and part. So the whole address looks like http://someserver.info/service/content/get?id=1&part=1
(Answered in the comments and question edits by OP. Moved here. See Question with no answers, but issue solved in the comments (or extended in chat) )
The OP wrote:
The authorization token in Zimbra called ZM_AUTH_TOKEN so you need to put your authtoken in cookies like this:
wr.CookieContainer = new CookieContainer();
wr.CookieContainer.Add(new Uri(url), new Cookie("ZM_AUTH_TOKEN", rc.AuthToken));
You don't need to put the auth headers then, the request will work

Weird paypal api issue

I just started using the Paypal API and I'm stuck on this problem.
I generate a paypal request in code and when I send it I get back the following.
TIMESTAMP=2011-05-16T01:26:37Z
CORRELATIONID=6d4327d15421f
ACK=Failure
L_ERRORCODE0=10001
L_SHORTMESSAGE0=Internal Error
L_LONGMESSAGE0=Timeout processing request
When I run through the debugger and copy the generated request url and paste it into my web browser, I get a success response....
I'm sending the request like this - c#
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
WebResponse response = req.GetResponse();
The same request, but one sent by code, and one copied to the browser produces to different results. Why is that?
I got same problem. When remove the
request.Method ="POST";
line, problem is solved.

C# REST client sending data using POST

I'm trying to send a simple POST request to a REST web service and print the response (code is below, mostly taken from Yahoo! developer documentation and the MSDN code snippets provided with some of the documentation). I would expect the client to send:
Request Method: POST (i.e. I expect $_SERVER['REQUEST_METHOD'] == 'POST' in PHP)
Data: foo=bar (i.e. $_POST['foo'] == 'bar' in PHP)
However, it seems to be sending:
Request Method: FOO=BARPOST
Data: (blank)
I know the API works as I've tested it with clients written in Python and PHP, so I'm pretty sure it must be a problem with my C#. I'm not a .NET programmer by trade so would appreciate any comments/pointers on how to figure out what the problem is - I'm sure it's something trivial but I can't spot it myself.
uri, user and password variables are set earlier in the code - they work fine with GET requests.
request = (HttpWebRequest) WebRequest.Create(uri);
request.Credentials = new NetworkCredential(user, password);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded";
string postData = "foo=bar";
request.ContentLength = postData.Length;
StreamWriter postStream = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
postStream.Write(postData);
postStream.Close();
response = (HttpWebResponse) request.GetResponse();
The REST API is written in PHP, and the $_POST array is empty on the server when using the C# client.
Eventually found the HttpWebRequest.PreAuthenticate property which seems to solve the problem if the code is edited like so:
request = (HttpWebRequest) WebRequest.Create(uri);
request.PreAuthenticate = true;
request.Credentials = new NetworkCredential(user, password);
request.Method = WebRequestMethods.Http.Post;
From the documentation I presume this forces authentication before the actual POST request is sent. I'm not sure why the class doesn't do this automatically (libraries for other languages make this process transparent, unless you explicitly turn it off), but it has solved the problem for me and may save someone else another 2 days of searching and hair-pulling.
For what it's worth, PreAuthenticate doesn't need to be set for GET requests, only POST, although if you do set it for a GET request everything will still work, but take slightly longer.

C# - Consuming REST web service over https

What's the best way to consume secure REST web service in C#? Web Service username and password are supplied in URL...
Several options:
HttpWebRequest class. Powerful but sometimes complex to use.
WebClient class. Less features, but should work for simpler web services, and much simpler.
The new HttpClient in the WCF REST Starter Kit. (The Starter Kit is a separate download, not a part of the .NET Framework).
Use WebRequest class to make the request and HttpWebResponse to get the response.
I used following code for consuming webservice.My user name,password and Url are saved in variables UserName,Pwd and Url respectively.
WebRequest Webrequest;
HttpWebResponse response;
Webrequest = WebRequest.Create(Url);
byte[] auth1 = Encoding.UTF8.GetBytes(UserName + ":" + Pwd);
Webrequest.Headers["Authorization"] = "Basic " + System.Convert.ToBase64String(auth1);
Webrequest.Method = "GET";
Webrequest.ContentType = "application/atom+xml";
response = (HttpWebResponse)Webrequest.GetResponse();
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
string Response = streamReader.ReadToEnd();
Response string will be available in variable Response.
I hope the password in the URL is somwhow encrypted :). Maybe this will help you:
http://social.msdn.microsoft.com/forums/en-US/wcf/thread/3c8db0bf-984e-426b-b068-d80165ed1b37/
Based on the little information you provided I would say that using the HttpWebRequest class is your best option.
It is relatively easy to use, there are lots of examples of how to use it and it will work with any media-type the REST interface delivers. You have full access to Http status codes, and Http Headers.
What more can you ask for?

Categories

Resources