HttpWebResponse not responding from PHP - c#

So I have this code in C#.
private void SendMessage()
{
// this is what we are sending
string post_data = "loginIdPost=" + 2 + "&" + "contentPost=" + absenceInputField.text;
string uri = "<URI IS HERE>";
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(uri); request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
byte[] postBytes = Encoding.ASCII.GetBytes(post_data);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine(new StreamReader(response.GetResponseStream()).ReadToEnd());
Debug.Log(new StreamReader(response.GetResponseStream()).ReadToEnd());
Debug.Log(response.StatusCode);
Console.WriteLine(response.StatusCode);
}
It sends some information to a PHP file, which then puts data into my database. The data is being successfully sent, but the HttpWebResponse is coming back blank. It returns "", an empty string.
This is my PHP code.
<?php
//Id
if (isset($_POST["loginIdPost"]))
{
$loginId = $_POST["loginIdPost"];
}
else
{
$loginId = null;
}
//Content
if (isset($_POST["contentPost"]))
{
$content = $_POST["contentPost"];
}
else
{
$content = null;
}
try
{
$conn = new PDO("Connection String");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
print("Error connecting to SQL Server.");
die(print_r($e));
}
$sth = $conn->prepare('Sql Query is here');
$sth->execute('details of execution are here');
echo "Success";
//Check Connection
if(!$conn)
{
die("Connection Failed. ". mysqli_connect_error());
}
?>
Does anyone know why I'm getting an empty string back, when I'd expect to be getting "Success" back. Again, no errors in the php code as the SQL query does insert data into my database.

I managed to fix it by just removing Console.Writeline.

Related

Http post request to send form data in image format

Hi I have below code to send the data, but in return I get server error with error code 500, the file is
not getting sent through the request
Can anyone tell me what I am doing wrong
FileStream rdr = new FileStream("C:/Users/AR485UY/Desktop/Test1.pdf", FileMode.Open)
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("url" );
string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
req.Method = "POST";
req.ContentLength = rdr.Length;
req.ContentType = "multipart/form-data; boundary=" +boundary;
req.AllowWriteStreamBuffering = true;
Stream reqStream = req.GetRequestStream();
byte[] inData = new byte[rdr.Length];
int len = Convert.ToInt32(rdr.Length);
int bytesRead = rdr.Read(inData, 0, len);
reqStream.Write(inData, 0, len);
rdr.Close();
req.GetResponse();
reqStream.Close();
HTTP 500 Internal Server Error server error response code indicates that the server encountered an unexpected condition that prevented it from fulfilling the request.
if it never work :
Most likely have to validate your server side api,script,logs,events,diagnostics trace,file size limits.
Also try another approach in c#:
try
{
using(WebClient client = new WebClient())
{
string myFile = #"C:/Users/AR485UY/Desktop/Test1.pdf";
client.Credentials = CredentialCache.DefaultCredentials;
client.UploadFile(url, "POST", myFile);
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}

C# python http post to C# httpwebrequest

i try to figure it out the black box of the server side that code by python for sending http post. In C# i trying to use httpwebrequest and httpwebresponse to send and receive message back from the server side.
Below is the python code:
**# Request login to server**
import httplib, urllib, requests
import sys, time
from requests.adapters import HTTPAdapter
import select, socket
s = requests.Session()
url = 'http://192.168.1.1/request_login'
data = 'user.login(test,test)' #login account and password set here
r = s.post(url, data=data)
if r.status_code != 200:
print "Failed loging in (%d)" % (r.status_code)
sys.exit(-1)
**# send key file to server**
url = 'http://192.168.1.1/request_sendfile'
files = {'file': (data_xml, open(data_xml, 'rb'), 'application/x-binary', {'Expires': '0'})} # **Don't understand this format**
r = s.post(url, files=files, timeout=30.0)
if r.status_code != 200:
print "Failed sending data file (%d, %s)" % (r.status_code, r.reason)
url = 'http://192.168.1.1/request_sendfile'
data = 'reader.view_log(4)'
r = s.post(url, data=data)
if r.status_code != 200:
print "Failed loging in (%d)" % (r.status_code)
sys.exit(-3)
print "Logs: "
print r.content
sys.exit(-4)
Above is the code for login and sending file to server in one session, i try to use C# do the same way.
I set two http request at the same time, however for the login is success while try to get second http request i get an error of "400" doesn't understand context of verb.
Below is the C# code:
private void httpost()
{
try
{
string Url = "http://192.168.1.1/request_login";
string Urls = "http://192.168.1.1/request_sendfile";
HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
HttpWebRequest requests = HttpWebRequest.Create(Urls) as HttpWebRequest;
string result = null;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "login";
string param = "user.login(test,test)";
byte[] bs = Encoding.ASCII.GetBytes(param);
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse response = request.GetResponse())
{
StreamReader sr = new StreamReader(response.GetResponseStream());
HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
if(resp.StatusCode == HttpStatusCode.OK)
{
richTextBox1.AppendText("Login Response Status:" + resp.StatusCode + "\n");
}
else
{
richTextBox1.AppendText("Login Response Failed: " + resp.StatusCode + "\n");
}
request.KeepAlive = true;
result = sr.ReadToEnd();
sr.Close();
}
using (Stream importFile = requests.GetRequestStream())
{
FileStream fs = File.OpenRead(#"data.xml");
byte[] bytes = ReadWholeArray(fs); // turn xml file to byte function
requests.ContentType = "application/x-binary";
requests.Method = "POST";
importFile.Write(bytes, 0, bytes.Length);
}
using (WebResponse responses = requests.GetResponse())
{
StreamReader srs = new StreamReader(responses.GetResponseStream());
result = srs.ReadToEnd();
srs.Close();
}
}
catch (Exception ex)
{
richTextBox1.AppendText("Exception Throw:" + ex.Message);
}
}
I try the python code it request login and send file at the same time.
And below is the code that i don't understand.
files = {'file': (data_xml, open(data_xml, 'rb'), 'application/x-binary', {'Expires': '0'})}

curl login script to visual c#

I have the working cURL script:
curl --insecure --data 'username=xxxx&password=xxxx' --dump-header headers https://$ipAddress/login
Trying to do the same thing on Visual C# but it does not work:
private void myExamplelogin(string ipAddress)
{
try
{
string user = xxxx;
string pass = xxxx;
string url = "https://" + ipAddress + "/login";
ServicePointManager.ServerCertificateValidationCallback = (obj, x509Certificate, chain, errors) => true;
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
string postData = "username=" + user + "&password=" + pass;
byte[] byteArray = Encoding.ASCII.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
}
catch (Exception e)
{
MessageBox.Show("error: " + e.Message);
}
}
I am getting "The remote server returned an error: (503) Server Unavailable". But when I try connect manually, the server is OK.
What seems to be wrong with code?

Error : 413 Request Entity Too Large in C# WinForm Application

I am trying to send JSON Object to Server for data synchronization.
This JSON object contain non-synchronized images and their data.
Real problem is not with he JSON or the Synchronization code.
But it is with the size of the Request i am sending to the server.
if the size cross the limit 1.1MB then i Got this message
The remote server returned an error: (413) Request Entity Too Large.
Please Help me. It is pur C# application not the WCF application.
Domain Hosting provider is Godady.com.
Using Apache server and PHP script.
Every this is working fine for smaller size. but it give exception error when size cross 1.1MB.
Here is My Request Code.
public string SubmitData(string poststring)
{
string result ="false";
if (poststring.ToLower() == "empty")
{
result = "empty";
return result;
}
try
{
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = poststring;
byte[] data = encoding.GetBytes(postData);
WebRequest request = WebRequest.Create("http://blunor.com/dark/data.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Credentials = CredentialCache.DefaultCredentials;
request.ContentLength = data.Length;
Stream stream = request.GetRequestStream();
showMessageBox(data.Length.ToString(), "Message", 1);
stream.Write(data, 0, data.Length);
stream.Close();
WebResponse response = request.GetResponse();
stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
// this block of code check if response is +ve or negtive..
string res_num = sr.ReadToEnd();
if (res_num == "1")
{
result = "true";
}
else
{
result = "false";
}
//block end here.....
sr.Close();
stream.Close();
return result;
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message);
}
return result;
}
For Server php post_max_size = 128M and Upload_max_filesize = 32M
Please Help......

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?

Categories

Resources