Http post request to send form data in image format - c#

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);
}

Related

HttpWebResponse not responding from PHP

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.

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......

Quickblox : Getting error during send push notification with c# (The remote server returned an error: (422) Unprocessable Entity.)

I'm getting an error when sending push notifications with c# (The remote server returned an error: (422) Unprocessable Entity.). I am sending notification to all possible devices.
Then I am getting an error on this line
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
And here is the code :
try
{
String token = GetToken();
HttpWebRequest httpWReq;
httpWReq = (HttpWebRequest)WebRequest.Create(System.Configuration.ConfigurationManager.AppSettings["QuickUrl"].ToString().Trim() + "events.xml");
byte[] plainTextBytes = System.Text.Encoding.UTF8.GetBytes("Pending Request Notification");
string base64Msg = System.Convert.ToBase64String(plainTextBytes);
String postData = "event[notification_type]=push";
postData += "&event[environment]=development";
postData += "&event[message]=" + base64Msg;
postData += "&event[ios_badge]=" + userPendingFriendRequestCount;
postData += "&event[ios_sound]=default";
postData += "&event[user][ids]={" + QuickBloxID + "}";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(postData);
httpWReq.UserAgent = ".NET Framework Test Client";
httpWReq.Method = "POST";
httpWReq.ContentLength = data.Length;
httpWReq.Headers["QuickBlox-REST-API-Version"] = "0.1.0";
httpWReq.Headers["QB-Token"] = token;
using (Stream stream = httpWReq.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();//The remote server returned an error: (422) Unprocessable Entity.
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
XDocument xmlDoc = XDocument.Parse(responseString);
IsNotificationSent = true;
}
catch (Exception ex)
{
// new ErrorLogger().LogException(ex, "QBBAL-->addupdateDriverUserInQuickBlox");
}

HttpWebRequest Issue to remote server

I'm trying to upload files to a remote server (windows server 2008 R2) from my asp.net 1.1 (C#) Windows application (I know.. It's really old, sadly, that's what we have). When I try to upload, it's giving me an error: "The remote server returned an error: (404) Not Found.".
Here's the code I'm using:
Any ideas?
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uploadUrl);
req.Credentials = new NetworkCredential(uName,pwd);
req.Method = "PUT";
req.AllowWriteStreamBuffering = true;
// Retrieve request stream
Stream reqStream = req.GetRequestStream();
// Open the local file
FileStream rdr = new FileStream(txt_filename.Text, FileMode.Open);
// Allocate byte buffer to hold file contents
byte[] inData = new byte[4096];
// loop through the local file reading each data block
// and writing to the request stream buffer
int bytesRead = rdr.Read(inData, 0, inData.Length);
while (bytesRead > 0)
{
reqStream.Write(inData, 0, bytesRead);
bytesRead = rdr.Read(inData, 0, inData.Length);
}
rdr.Close();
reqStream.Close();
req.GetResponse();
The uploadUrl is like this: http://10.x.x.x./FolderName/Filename
Please use "POST" method instead of "PUT" and I guess it will work.
Edit:
Check the code below, it will help you.
public void UploadFile()
{
string fileUrl = #"enter file url here";
string parameters = #"image=" + Convert.ToBase64String(File.ReadAllBytes(fileUrl));
WebRequest req = WebRequest.Create(new Uri("location url here"));
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(parameters);
try
{
req.ContentLength = bytes.Length;
Stream s = req.GetRequestStream();
s.Write(bytes, 0, bytes.Length);
s.Close();
}
catch (WebException ex)
{
throw ex; //Request exception.
}
try
{
WebResponse res = req.GetResponse();
StreamReader sr = new StreamReader(req.GetResponseStream());
}
catch (WebException ex)
{
throw ex; //Response exception.
}
}
Enter fileUrl variable correctly and take care of uri while creating WebRequest instance, write the url of the locating folder.

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