Send json data to remote server for authentication - c#

I want to post authentication details to a remote server, sending username, database name and password. My server is running on Ubuntu. But i get error Invalid JSON data: ''
"POST / HTTP/1.1" 400 -
I am new to working on this platform, help me with where i am doing it wrong. Below is my code:
private void SendDataButton_Click(object sender, RoutedEventArgs e)
{
string url = "http://200.84.100.211:9875";
string call = url + "/web/session/authenticate";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(call) as HttpWebRequest;
request.ContentType = "application/json";
request.Method = "POST";
request.BeginGetResponse(new AsyncCallback(SendData), request);
}
void SendData(IAsyncResult callbackResult)
{
HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
Stream postStream = myRequest.EndGetRequestStream(callbackResult);
string postData = "{'db':'demo_shruti','login':'admin','password':'admin'}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
myRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), myRequest);
}
void FinishWebRequest(IAsyncResult callbackResult)
{
HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
string responseString = "";
Stream streamResponse = response.GetResponseStream();
StreamReader reader = new StreamReader(streamResponse);
responseString = reader.ReadToEnd();
streamResponse.Close();
reader.Close();
response.Close();
string result = responseString;
}

Related

c# HttpWebRequest get response string

I'm trying to send some data through HTTPS Post without certification.
But I'm getting null however that response status code is OK.
Why is this? Any help would be greatly appreciated.
I want to receive "hello" string from https://test.com/post_test.php.
I saw many examples related to this, but none is working for me.
Does anyone know what I am missing?
Can some one guide me how to do that?
Thanks in advance!
c# code:
private static bool ValidateRemoteCertificate(object sender,X509Certificate certificate,X509Chain chain,SslPolicyErrors policyErrors)
{
return true;
}
private String SendHttpWebPost(string strUrl, string strData)
{
string result = string.Empty;
ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(ValidateRemoteCertificate);
HttpWebRequest request = null;
HttpWebResponse response = null;
try
{
Uri url = new Uri(strUrl);
request = (HttpWebRequest)WebRequest.Create(url);
request.Method = WebRequestMethods.Http.Post;
request.KeepAlive = true;
request.Timeout = 5000;
// encoding
byte[] data = Encoding.UTF8.GetBytes(strData);
request.ContentType = "application/json";
request.ContentLength = data.Length;
// send request
Stream dataStream = request.GetRequestStream();
dataStream.Write(data, 0, data.Length);
dataStream.Flush();
dataStream.Close();
// get response
response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
string strStatus = ((HttpWebResponse)response).StatusDescription;
StreamReader streamReader = new StreamReader(responseStream);
result = streamReader.ReadToEnd();
// close connection
streamReader.Close();
responseStream.Close();
response.Close();
}
catch (Exception ex)
{
return ex.Message;
}
return result;
}
private void Form1_Load(object sender, EventArgs e)
{
MessageBox.Show(SendHttpWebPost("https://test.com/post_test.php", "data=hello"));
}
php code:
<?php
echo($_REQUEST["data"]);
?>
Why don't you just simply request the Url without any fancy?
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(strUrl);
Request.Method = "GET";
Request.KeepAlive = true;
HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();
if (Response.StatusCode == HttpStatusCode.OK) {
....
}

Http POST in wp8

As I have gone through the examples,I have come across only asynchronous http web request having callback methods,like:-
private void getList(string restApiPath, Dictionary<string, string> output, Type type, string label)
{
webRequest = (HttpWebRequest)WebRequest.Create(restApiPath);
path = restApiPath;
labelValue = label;
webRequest.Method = "POST";
webRequest.ContentType = Globals.POST_CONTENT_TYPE;
webRequest.Headers["st"] = MPFPConstants.serviceType;
webRequest.BeginGetRequestStream(result =>
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
// End the stream request operation
Stream postStream = request.EndGetRequestStream(result);
// Create the post data
string reqData = Utils.getStringFromList(output);
string encode = RESTApi.encodeForTokenRequest(reqData);
byte[] byteArray = Encoding.UTF8.GetBytes(encode);
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
request.BeginGetResponse(new AsyncCallback(GetResponseCallbackForSpecificConditions), request);
}, webRequest);
}
private void GetResponseCallbackForSpecificConditions(IAsyncResult ar)
{
//code
}
Kindly Suggest me if we can make a synchronous httpwebrequest for wp8?
Why not try this, it works in a Desktop app:
using (Stream TextRequestStream = UsedWebRequest.GetRequestStream())
{
TextRequestStream.Write(ByteArray, 0, ByteArray.Length);
TextRequestStream.Flush();
}
HttpWebResponse TokenWebResponse = (HttpWebResponse)UsedWebRequest.GetResponse();
Stream ResponseStream = TokenWebResponse.GetResponseStream();
StreamReader ResponseStreamReader = new StreamReader(ResponseStream);
string Response = ResponseStreamReader.ReadToEnd();
ResponseStreamReader.Close();
ResponseStream.Close();
Why not try restsharp?
sample POST code looks like,
RestClient _authClient = new RestClient("https://sample.com/account/login");
RestRequest _credentials = new RestRequest(Method.POST);
_credentials.AddCookie(_cookie[0].Name, _cookie[0].Value);
_credentials.AddParameter("userLogin", _username, ParameterType.GetOrPost);
_credentials.AddParameter("userPassword", _password, ParameterType.GetOrPost);
_credentials.AddParameter("submit", "", ParameterType.GetOrPost);
RestResponse _credentialResponse = (RestResponse)_authClient.Execute(_credentials);
Console.WriteLine("Authentication phase Uri : " + _credentialResponse.ResponseUri);

Parsing POST request data with FiddlerCore

I'm tring to capture a local POST requset and parse its data.
For testing only, the FiddlerCore should only response with the data it has parsed.
Here's the code of the FidlerCore encapsulation:
private void FiddlerApplication_BeforeRequest(Session oSession)
{
if (oSession.hostname != "localhost") return;
eventLog.WriteEntry("Handling local request...");
oSession.bBufferResponse = true;
oSession.utilCreateResponseAndBypassServer();
oSession.oResponse.headers.HTTPResponseStatus = "200 Ok";
oSession.oResponse["Content-Type"] = "text/html; charset=UTF-8";
oSession.oResponse["Cache-Control"] = "private, max-age=0";
string body = oSession.GetRequestBodyAsString();
oSession.utilSetResponseBody(body);
}
Here's the code of the request sender:
const string postData = "This is a test that posts this string to a Web server.";
try
{
WebRequest request = WebRequest.Create("http://localhost/?action=print");
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
request.ContentType = "text/html";
request.Method = "POST";
using (Stream stream = request.GetRequestStream())
{
stream.Write(byteArray, 0, byteArray.Length);
}
using (WebResponse response = request.GetResponse())
{
txtResponse.Text = ((HttpWebResponse)response).StatusDescription;
using (Stream stream = response.GetResponseStream())
{
using (StreamReader streamReader = new StreamReader(stream))
{
string responseFromServer = streamReader.ReadToEnd();
streamReader.Close();
txtResponse.Text = responseFromServer;
}
}
}
}
catch (Exception ex)
{
txtResponse.Text = ex.Message;
}
I'm getting the following error:
The server committed a protocol violation. Section=ResponseStatusLine
What am I doing wrong?
Got it to work by changing:
WebRequest request = WebRequest.Create("http://localhost/?action=print");
to
WebRequest request = WebRequest.Create("http://localhost:8877/?action=print");
Calling this URL from a browser is intercepted by FiddlerCore correctly, without having to specify the port number. I did not think I should have inserted the listening port, since FiddlerCore should intercept all traffic, right?

Add param POST request using HttpWebRequest async windows phone 8 - JSON [duplicate]

I need to call a method from a webservice, so I've written this code:
private string urlPath = "http://xxx.xxx.xxx/manager/";
string request = urlPath + "index.php/org/get_org_form";
WebRequest webRequest = WebRequest.Create(request);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.
webRequest.ContentLength = 0;
WebResponse webResponse = webRequest.GetResponse();
But this method requires some parameters, as following:
Post data:
_username:'API USER', // api authentication username
_password:'API PASSWORD', // api authentication password
How can I add these parameters into this Webrequest?
Use stream to write content to webrequest
string data = "username=<value>&password=<value>"; //replace <value>
byte[] dataStream = Encoding.UTF8.GetBytes(data);
private string urlPath = "http://xxx.xxx.xxx/manager/";
string request = urlPath + "index.php/org/get_org_form";
WebRequest webRequest = WebRequest.Create(request);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = dataStream.Length;
Stream newStream=webRequest.GetRequestStream();
// Send the data.
newStream.Write(dataStream,0,dataStream.Length);
newStream.Close();
WebResponse webResponse = webRequest.GetResponse();
If these are the parameters of url-string then you need to add them through '?' and '&' chars, for example http://example.com/index.aspx?username=Api_user&password=Api_password.
If these are the parameters of POST request, then you need to create POST data and write it to request stream. Here is sample method:
private static string doRequestWithBytesPostData(string requestUri, string method, byte[] postData,
CookieContainer cookieContainer,
string userAgent, string acceptHeaderString,
string referer,
string contentType, out string responseUri)
{
var result = "";
if (!string.IsNullOrEmpty(requestUri))
{
var request = WebRequest.Create(requestUri) as HttpWebRequest;
if (request != null)
{
request.KeepAlive = true;
var cachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
request.CachePolicy = cachePolicy;
request.Expect = null;
if (!string.IsNullOrEmpty(method))
request.Method = method;
if (!string.IsNullOrEmpty(acceptHeaderString))
request.Accept = acceptHeaderString;
if (!string.IsNullOrEmpty(referer))
request.Referer = referer;
if (!string.IsNullOrEmpty(contentType))
request.ContentType = contentType;
if (!string.IsNullOrEmpty(userAgent))
request.UserAgent = userAgent;
if (cookieContainer != null)
request.CookieContainer = cookieContainer;
request.Timeout = Constants.RequestTimeOut;
if (request.Method == "POST")
{
if (postData != null)
{
request.ContentLength = postData.Length;
using (var dataStream = request.GetRequestStream())
{
dataStream.Write(postData, 0, postData.Length);
}
}
}
using (var httpWebResponse = request.GetResponse() as HttpWebResponse)
{
if (httpWebResponse != null)
{
responseUri = httpWebResponse.ResponseUri.AbsoluteUri;
cookieContainer.Add(httpWebResponse.Cookies);
using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
}
}
}
responseUri = null;
return null;
}
For doing FORM posts, the best way is to use WebClient.UploadValues() with a POST method.
Hope this works
webRequest.Credentials= new NetworkCredential("API_User","API_Password");
I have a feeling that the username and password that you are sending should be part of the Authorization Header. So the code below shows you how to create the Base64 string of the username and password. I also included an example of sending the POST data. In my case it was a phone_number parameter.
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(_username + ":" + _password));
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Request);
webRequest.Headers.Add("Authorization", string.Format("Basic {0}", credentials));
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.AllowAutoRedirect = true;
webRequest.Proxy = null;
string data = "phone_number=19735559042";
byte[] dataStream = Encoding.UTF8.GetBytes(data);
request.ContentLength = dataStream.Length;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader streamreader = new StreamReader(stream);
string s = streamreader.ReadToEnd();
The code below differs from all other code because at the end it prints the response string in the console that the request returns. I learned in previous posts that the user doesn't get the response Stream and displays it.
//Visual Basic Implementation Request and Response String
Dim params = "key1=value1&key2=value2"
Dim byteArray = UTF8.GetBytes(params)
Dim url = "https://okay.com"
Dim client = WebRequest.Create(url)
client.Method = "POST"
client.ContentType = "application/x-www-form-urlencoded"
client.ContentLength = byteArray.Length
Dim stream = client.GetRequestStream()
//sending the data
stream.Write(byteArray, 0, byteArray.Length)
stream.Close()
//getting the full response in a stream
Dim response = client.GetResponse().GetResponseStream()
//reading the response
Dim result = New StreamReader(response)
//Writes response string to Console
Console.WriteLine(result.ReadToEnd())
Console.ReadKey()

NTLM Authentication implementation error in wp7

it gives me an error when I am trying to authenticate with server using NTLM in wp7 "The remote server returned an error: NotFound."
private void callWebservice(object sender, RoutedEventArgs e)
{
NetworkCredential credentials = new NetworkCredential(userName, Password, domain);
HttpWebRequest request = CreateWebRequest(url, credentials);
XDocument soapEnvelope = CreateSoapEnvelope(soapEnvelope );
InsertSoapEnvelopeIntoWebRequest(soapEnvelope, request);
}
private static HttpWebRequest CreateWebRequest(string url, NetworkCredential credentials)
{
string action = link;// my action link
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Credentials = credentials;
req.Headers["SOAPAction"] = action;
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";
return req;
}
private static XDocument CreateSoapEnvelope(string content)
{
XDocument soapEnvelopeXml = XDocument.Parse(content);
return soapEnvelopeXml;
}
private static void InsertSoapEnvelopeIntoWebRequest(XDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
webRequest.BeginGetRequestStream((IAsyncResult asynchronousResult) =>
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = request.EndGetRequestStream(asynchronousResult);
soapEnvelopeXml.Save(postStream);
postStream.Close();
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}, webRequest);
}
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
//do whatever with the response
MessageBox.Show(responseString);
streamResponse.Close();
streamRead.Close();
response.Close();
}
authenticate with server using NTLM on wp7 insn't supported ,it is supported on wp8
the same code on wp8 it gives result

Categories

Resources