Changing HTTP Request to HTTPS, message content seems to be lost - c#

This is not a subject I am strong in so I apologize ahead of time if I say something ridiculous.
I have developed an HTTP service using Mule. I have it functioning perfectly when I connect directly to the service and send data using a test harness I wrote in C#.
As the final part of my testing, I need to send it to an HTTPS URL that is supposed to "decrypt" the message and forward it to my service. When I send a message to the HTTPS URL, it gets forwarded to my service but the message contents appear empty and therefore does not get processed. I understand that I may have to add some "encryption" to my Test Harness but I have been researching how to do this all day and nothing I have found is answering my question.
Here is an example of the code I am using for the simple HTTP request:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["HttpDestination"].ToString());
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length;
using (Stream strm = req.GetRequestStream())
{
strm.Write(data, 0, data.Length);
}
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
What do I need to change here to make this work?

Here is the solution that I discovered here. I needed to add the following line:
req.ProtocolVersion = System.Net.HttpVersion.Version10;
Without this, a timeout was occurring when getting the request stream and the content was never being sent, only the headers.

Related

MANDATORY_FIELDS_MISSING: lastname does not have a value

I am getting very frustrated. I am using .NET to import a bunch of leads in to vTiger 6.2.0. I am using a simple web request that i have seen plenty of examples working. I have also seen it working from my dev environment and i would intermittently get the above response from the service. I have moved over to using live data (still from my machine). There is no reason for the imports to fail as they all contain a last name.
I have scoured the internet for any relevant information and have come up blank.
I am using a post request in the following way...
byte[] bytes = Encoding.ASCII.GetBytes(requestParameters);
WebRequest request = HttpWebRequest.Create(url) as WebRequest;
request.ContentLength = bytes.Length;
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
using (var swRequest = request.GetRequestStream())
{
swRequest.Write(bytes, 0, bytes.Length);
}
The request URL (minus the domain) looks like this: /webservice.php?operation=create
The requestParameters variable looks like this (anonymised the data where there was data):
operation=create&sessionName=660f54e47e39358ce&element={"leadsource":"blaah","cf_757":"blaah","salutationtype":"0.","firstname":"blaah","lastname":"blaah","email":"blaah","phone":"blaah","description":"blaah","cf_833":"blaah","emailoptout":"1","cf_761":"1","cf_759":"1","cf_763":"1","assigned_user_id":"19x5"}&elementType=Leads
in the response i get back i receive the error below for nearly every record.
MANDATORY_FIELDS_MISSING: lastname does not have a value.
Last name and assigned user are the only mandatory values needed and the assigned user is the id returned from the login.
Is anybody able to provide some help on this? i have spent hours on it with no success.

Does the WebResponse for Windows Phone 8 skip set-cookie headers

I am experiencing some strange behavior with a Windows Phone 8 app that I am building and I hope someone here has some experience with it.
I am reading a website using a normal HttpWebRequest and expecting a cookie as a response. However, somehow, I am not getting the Set-cookie header back in my WebResponse. I have created the same functionality under WPF and it works as normal - returns the Set-cookie header in the response.
I have also tried looking at the CookieContainer of the response, but it is also empty.
Here is the code that I am using for this. Note: the same piece of code (without the async stuff) works correct in WPF and returns the Set-Cookie header. I can post it as well if necessary:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.mysite.com/login");
request.Method = HttpMethod.Post;
request.AllowAutoRedirect = false;//normally there is a redirect in place
postData = "username=1234&password=2345";
var data = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = await Task.Factory.FromAsync<Stream>(request.BeginGetRequestStream, request.EndGetRequestStream, null))
{
await stream.WriteAsync(data, 0, data.Length);
stream.Close();
}
using (var response = await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null))
{
return response.Headers["set-cookie"];
}
As a result of this, I am getting some response headers (such as content-type and server specific ones) but not the Set-Cookie one.
I've done some more tests and the set-cookie header is omitted only on the Windows Phone Emulator. When debugging with an actual device, the header is received as expected.
It is still pretty strange to me why the emulator behaves this way. I saw many posts on issues with http-only cookies in the emulator but none with a concrete reason.
UPDATE:
Testing on the 8.0.10322 emulator works just fine - cookies are handled correctly.It looks as the default phone emulator does something fishy with the cookies.

In C#, is it possible to open a URL in the background, without opening a browser?

My code needs to supply some information to a server via a php script.
Basically I want to call www.sitename.com/example.php?var1=1&var2=2&var3=3 but I don't want the browser to open, so Process.Start(URL); won't work.
Since I come to this site to learn and not to get answers, mostly, I will explain what I've done so far and the errors I have gotten. If you know a solution anyway, feel free to skip the next part.
I have looked around, and I saw a solution for using POST:
ASCIIEncoding encoding=new ASCIIEncoding();
string postData="var1=1&var2=2&var3=3";
byte[] data = encoding.GetBytes(postData);
// Prepare web request...
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://localhost/site.php");
myRequest.Method = "POST";
myRequest.ContentType="application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream=myRequest.GetRequestStream();
// Send the data.
newStream.Write(data,0,data.Length);
newStream.Close();
However, I require the use of GET not POST. At first I thought the solution might be to change myRequest.Method = "POST"; to GET, but this didn't work because that's not how GET works, it pulls data from the URL.
So, then I attempted to change the previous code to:
HttpwebRequest myRequest= (HttpWebRequest)WebRequest.Create("http://localhost/site.php" + postData);
Stream newStream = myRequest.GetRequestStream();
newStream.Close()
Under the logic that it would call the URL, which would (hopefully) initiate the GET_ request on the php script, and then life would be dandy. This however resulted in the following error:
A first chance exception of type 'System.Net.ProtocolViolationException' occurred in System.dll
An unhandled exception of type 'System.Net.ProtocolViolationException' occurred in System.dll
Additional information: Cannot send a content-body with this verb-type.
Any help is appreciated, and thanks.
string postData="var1=1&var2=2&var3=3";
// Prepare web request...
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(
"http://yourserver/site.php?" + postData);
myRequest.Method = "GET";
var resp =(HttpWebResponse) myRequest.GetResponse();
var result = new StreamReader(resp.GetResponseStream()).ReadToEnd();
Or maybe even simpler:
var data = new WebClient().DownloadString("http://yourserver/site.php?var1=1&var2=2&var3=3");
See the WebClient class for more options
You mostly seem to have gone down the right route:
string postData="var1=1&var2=2&var3=3";
// Prepare web request...
HttpwebRequest myRequest= (HttpWebRequest)WebRequest.Create(
"http://localhost/site.php?" + postData);
// Send the data.
myRequest.GetResponse();
Note that I've added the ? at the end of site.php.
We don't have to fiddle around with the request stream since that's all about putting things in the body of a request - and as you've stated, a GET request has its data in the URL, not in its body.
The easiest way is to use WebClient class. Using it it's just 2 lines of code, just supply your URL and use methods like DownloadString.

HTTPWebRequest Body Formatting

This is a stupidly trivial question, but I can't seem to find a proper example anywhere with more than one property being set. Basically, I'm trying to send a POST request with C#'s HTTPWebRequest library while specifying two different fields in the body of the request.
So far, I have this:
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byt = encoding.GetBytes("recipient=12345ABC");
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byt.Length;
Stream newStream = request.GetRequestStream();
newStream.Write(byt, 0, byt.Length);
Followed by the usual GetResponse() stuff. This works fine, everything's dandy, but I can't figure out how to specify multiple body elements, such as both of these:
recipient=12345ABC
body="testmessage"
I've tried separating them with a semicolon, an ampersand, and a comma, but the server keeps returning Error 400: Bad Request. Perhaps I'm just misunderstanding how this process works?
API docs were sloppily done. Actual parameter names were "recipients" and "text" - code worked fine after this change.
URL encoding in the body works fine, "recipients=12345ABC&text=This+is+URL+escaped+text" worked like a charm in either the URL itself or the POST body.

Can I send an empty HTTP POST WebRequest object from C# to IIS?

Do I need to just slap some random garbage data in a WebRequest object to get by the HTTP status code 411 restriction on IIS?
I have an HttpPost action method in an MVC 3 app that consumes a POST request with all the relevant information passed in the querystring (no body needed).
[HttpPost] public ActionResult SignUp(string email) { ... }
It worked great from Visual Studio's built in web host, Cassini. Unfortunately, once the MVC code was live on IIS [7.5 on 2008 R2], the server is pitching back an HTTP error code when I hit it from my outside C# form app.
The remote server returned an error:
(411) Length Required.
Here is the calling code:
WebRequest request = WebRequest.Create("http://somewhere.com/signup/?email=a#b.com");
request.Method = "POST";
using (WebResponse response = request.GetResponse())
using (Stream responseStream = response.GetResponseStream())
using (StreamReader responseReader = new StreamReader(responseStream)) {
// Do something with responseReader.ReadToEnd();
}
Turns out you can get this to go through by simply slapping an empty content length on the request before you send it.
WebRequest request = WebRequest.Create("http://somewhere.com/signup/?email=a#b.com");
request.Method = "POST";
request.ContentLength = 0;
Not sure how explicitly giving an empty length vs. implying one makes a difference, but IIS was happy after I did. There are probably other ways around this, but this seems simple enough.
I believe you are required to set a Content-Length header anytime you post a request to a web server:
http://msdn.microsoft.com/en-us/library/system.web.httprequest.contentlength.aspx
You could try a GET request to test it.

Categories