Send a String to server with http POST - http-post

I have a maxScript that requires to send the mac address of the user to a server and check if it is included in the allowed list.
I have to part fo getting the mac address and the server side is all set.
the only problem is that I want it to be sent by POST so there would be more security to it but I have no idea how to do that.

Okay, I finally figured it out. here is the complete code for getting the mac address and sending it to a server with HttpPost:
--Getting the mac address
NI = dotnetclass "System.Net.NetworkInformation.NetworkInterface";
NI.GetIsNetworkAvailable();
ALL = NI.GetAllNetworkInterfaces();
MACAddress = ALL[1].GetPhysicalAddress();
print (MACAddress.toString());
--Encoding the mac address so it is sendable
A = (dotNetClass "System.Text.Encoding");
PostData = "macaddress=" + MACAddress.toString();
MData = A.ASCII.GetBytes (PostData);
--Creating the Post request
Req = (dotNetClass "System.Net.WebRequest").Create ("http://ip.mdfplan.com/");
Req.Method = "Post";
Req.ContentType = "application/x-www-form-urlencoded";
Req.ContentLength = MData.count;
--Writing the data in the request
S = Req.GetRequestStream();
S.write MData 0 MData.count;
S.close();
--Sending the request and recieving the response
Res = Req.GetResponse();
ResStr = Res.GetResponseStream();
--Reading the respone
objReader = dotnetobject "System.IO.StreamReader" ResStr;
ResText = (objReader.ReadToEnd());

Related

Parse Rest API PUT not working for Unity WebGL

I am working on unity webgl build on our existing IOS running app. All the data about users are saving on Parse. I have implemented Rest API to communicate with Parse. Implemented Get and Post(without passing the method header) they are working fine but when i am trying to update the data using PUT :
string url = "https://api.parse.com/1/"
string ObjectID = "ERd99Q0kmd"
string CallLink = url + "classes/PlayerProfile/" + ObjectID ;
string jsonString = "{\"TotalCoins\":40}";
WWWForm form = new WWWForm();
var headers = form.headers;
headers["X-Parse-Application-Id"] = appID;
headers["X-Parse-REST-API-Key"] = restapikey;
headers["Content-Type"] = "application/json";
headers["Content-Length"] = jsonString.Length.ToString();
var encoding = new System.Text.UTF8Encoding();
WWW www = new WWW(CallLink,encoding.GetBytes(jsonString),headers);
yield return www;
if (www.error != null)
{
Debug.Log( "CallGet:Error:"+www.error);
}
else
{
Debug.Log("CallGet:Success:"+www.text);
}
It gives Bad Request error. I also tried the header "Method" it also give Bad Request but when i tried "X-HTTP-Method-Override" it works in unity editor but still it doesn't working in Browser and getting following Error :
Request header field X-HTTP-Method-Override is not allowed by
Access-Control-Allow-Headers in preflight response.
Please help me out how can i update the data.

How to check siteminder status using c#

hi I need to check the status of siteminder to see if its down or not. My current solution is to ping the policy servers of siteminder on a specified environment. Is there any way to check if Siteminder is up or down using c#? Thanks in advance
I have this code dumped into a google doc from when i was on a project that used siteminder a while back. hope that it helps
String urltest = "https://domain/authentication.fcc?target=https://domain/desired/stats/page.asp";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(urltest);
CredentialCache MyCredentialCache = new CredentialCache();
MyCredentialCache.Add(new Uri(uriTeste), "NTLM", new NetworkCredential("user", "password", "domain"));
req.Credentials = MyCredentialCache;
req.PreAuthenticate = false;
req.AllowAutoRedirect = true;
req.UnsafeAuthenticatedConnectionSharing = true;
req.Method = "POST";
req.Timeout = 100000;
HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();

SignalR .Net client fails to connect (upd: how to set auth. cookie?)

This thing is dragging me nuts.
I have a .net 4.0 console app and I have an MVC web app.
javascript clients can connect and talk to the server - no problems here...
but my .net client throws System.AggregateException with InnerException = "Unexpected character encountered while parsing value: <. Path...
so I created an empty MVC3 app, added SignalR libraries, and .net client surprisingly connects to that. But for some reason it doesn't to the other one. I've checked everything, both MVC3 apps, both use the same SignalR libs, the same NewtonsoftJson... I thought it must be something with the routing, I guess no - js client works.
var connection = new HubConnection("http://localhost:58746");
var hubProxy = connection.CreateProxy("myProxy");
connection.Start().Wait() // it fails here on Wait
What could it be?
UPD: I have figured... it's because FormsAuthentication on the server. Now is there any way to feed .ASPXAUTH cookie to SignalR so it can connect to the server?
The solution by Agzam was really helpful, but if anyone else uses the posted code it is critical that you close the HttpWebResponse before exiting GetAuthCookie. If you don't you will find that whenever you use SignalR to invoke a method on the server, the request (under most circumstances) will queue indefinitely on the client and will neither succeed nor fail.
Note. The original code worked in the test environment when everything was on my PC, but failed consistently when the website was hosted on a remote server.
here is the modified code I ended up using
private Cookie GetAuthCookie(string user, string pass)
{
var http = WebRequest.Create(_baseUrl+"Users/Login") as HttpWebRequest;
http.AllowAutoRedirect = false;
http.Method = "POST";
http.ContentType = "application/x-www-form-urlencoded";
http.CookieContainer = new CookieContainer();
var postData = "UserName=" + user + "&Password=" + pass + "&RememberMe=true&RememberMe=false&ReturnUrl=www.google.com";
byte[] dataBytes = System.Text.Encoding.UTF8.GetBytes(postData);
http.ContentLength = dataBytes.Length;
using (var postStream = http.GetRequestStream())
{
postStream.Write(dataBytes, 0, dataBytes.Length);
}
var httpResponse = http.GetResponse() as HttpWebResponse;
var cookie = httpResponse.Cookies[FormsAuthentication.FormsCookieName];
httpResponse.Close();
return cookie;
}
its a very minor change , but it will save you a lot of debugging time.
Ok... stupid me... SignalR failed to connect because it cannot breach server's Forms authentication. So what needed to be done is to get the auth cookie and stick it to the HubConnection.CookieContainer...
so I wrote this method method to login with a username and get the cookie:
private Cookie GetAuthCookie(string user, string pass)
{
var http = WebRequest.Create(_baseUrl+"Users/Login") as HttpWebRequest;
http.AllowAutoRedirect = false;
http.Method = "POST";
http.ContentType = "application/x-www-form-urlencoded";
http.CookieContainer = new CookieContainer();
var postData = "UserName=" + user + "&Password=" + pass + "&RememberMe=true&RememberMe=false&ReturnUrl=www.google.com";
byte[] dataBytes = System.Text.Encoding.UTF8.GetBytes(postData);
http.ContentLength = dataBytes.Length;
using (var postStream = http.GetRequestStream())
{
postStream.Write(dataBytes, 0, dataBytes.Length);
}
var httpResponse = http.GetResponse() as HttpWebResponse;
var cookie = httpResponse.Cookies[FormsAuthentication.FormsCookieName];
httpResponse.Close();
return cookie;
}
And used it like this:
var connection = new HubConnection(_baseUrl)
{
CookieContainer = new CookieContainer()
};
connection.CookieContainer.Add(GetAuthCookie(_user, _pass));
Works perfectly!
Just use this for reading cookies:
var cookie = response.Cookies[".AspNet.ApplicationCookie"];

Keep web sessions

I use an API that I first need to log in to and then I get access to view the nodes. These are the two urls that are used.
http://thewebpage.com/login.php?user=123&pass=123
http://thewebpage.com/get_nodes.php
The method im using to connect is the following
StreamConnection s = (StreamConnection)Connector.open(url);
InputStream input = s.openInputStream();
byte[] data = new byte[256];
int len = 0;
StringBuffer raw = new StringBuffer();
while( -1 != (len = input.read(data))) {
raw.append(new String(data, 0, len));
}
response = raw.toString();
When I connect to login.php I get the response from the server that im logged in, but the problem is when I call get_nodes.php I get the response "please login" because the session isn't stored.
Is there any way to solve this so I can access the nodes?
Thanks
I finally solved it by saving the cookie data from the login and then put the cookie in the other http request like this
Get cookie
HttpConnection connection = (HttpConnection)Connector.open(loginUrl);
String cookieData = connection.getHeaderField("Set-Cookie");
Set cookie
HttpConnection connection = (HttpConnection)Connector.open(nodeUrl);
connection.setRequestProperty("Cookie", cookieData);

WebClient NotFound error but working with HttpWebRequest/Response

In my WinPhone app I'm accessing a REST service.
At the beginnings I was using this code:
WebClient wc = new WebClient();
wc.Credentials = credentials;
wc.Headers["App-Key"] = appKey;
wc.DownloadStringCompleted +=
(o, args) => MessageBox.Show(args.Error == null ? "OK" : "Error");
wc.DownloadStringAsync(uri);
but it suddenly stopped working returning me a "The remote server returned an error: NotFound" error. After a google session and some clicks in the control panel, I didn't get it to work.
I decided to try this other way:
HttpWebRequest request = HttpWebRequest.CreateHttp(uri);
request.Credentials = credentials;
request.Headers["App-Key"] = appKey;
request.BeginGetResponse(asResult =>
{
var response = request.EndGetResponse(asResult) as HttpWebResponse;
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseString = reader.ReadToEnd();
Dispatcher.BeginInvoke(
() => MessageBox.Show(response.StatusCode.ToString()));
}, null);
and it works.
I also tried to run the first snipped pointing the URI to google's home page and it works (I had to remove the credentials, of course).
Can anyone explain what's going on?
UPDATE
I managed to get it working by replacing the
wc.Credentials = new NetworkCredentials(username, password);
with
wc.Headers["Authorization"] = "Basic someBase64encodedString";
but i still wonder what happened and which are the differences between the first and the second line.
PS: the test URI is: https://api.pingdom.com/api/2.0/checks but you will need an app-key from them.
When using the Credentials property, the HttpWebRequest implementation will wait the challenge response from server before to send the 'Authorization' header value.
But this can be an issue in some cases, so you have to force Basic authentication by providing directly the Authorization header.
Example when using a REST Client library like Spring.Rest :
RestTemplate template = new RestTemplate("http://example.com");
template.RequestInterceptors.Add(new BasicSigningRequestInterceptor("login", "password"));
string result = template.GetForObject<string>(uri);

Resources