473,224 Members | 1,597 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,224 software developers and data experts.

how to send data to webpage via post

Hi,
I want to send a report from a windows application to a web page like
'report.asp'

Currently i can send it via post method with a context like
local=En&Username=fatih&UserId=45&Firm=none
But the problem occures when i want to send a data with & sign (i.e:
Firm=F&B). I try to solve this problem with using boundary, but i failed.

Any idea!?

Fatih BOY
Nov 13 '05 #1
2 20715
I just found a class for this purpose.
Here is the code:

using System;
using System.Net;
using System.Text;
using System.IO;
using System.Collections;

namespace norvanco.http
{
/// <summary>
/// Allow the transfer of data files using the W3C's specification
/// for HTTP multipart form data. Microsoft's version has a bug
/// where it does not format the ending boundary correctly.
/// Written by: gr******@norvanco.com
/// </summary>
public class MultipartForm
{
/// <summary>
/// Holds any form fields and values that you
/// wish to transfer with your data.
/// </summary>
private Hashtable coFormFields;
/// <summary>
/// Used mainly to avoid passing parameters to other routines.
/// Could have been local to sendFile().
/// </summary>
protected HttpWebRequest coRequest;
/// <summary>
/// Used if we are testing and want to output the raw
/// request, minus http headers, out to a file.
/// </summary>
System.IO.Stream coFileStream;
/// <summary>
/// Difined to build the form field data that is being
/// passed along with the request.
/// </summary>
static string CONTENT_DISP = "Content-Disposition: form-data; name=";
/// <summary>
/// Allows you to specify the specific version of HTTP to use for
uploads.
/// The dot NET stuff currently does not allow you to remove the
continue-100 header
/// from 1.1 and 1.0 currently has a bug in it where it adds the
continue-100. MS
/// has sent a patch to remove the continue-100 in HTTP 1.0.
/// </summary>
public Version TransferHttpVersion
{get{return coHttpVersion;}set{coHttpVersion=value;}}
Version coHttpVersion;

/// <summary>
/// Used to change the content type of the file being sent.
/// Currently defaults to: text/xml. Other options are
/// text/plain or binary
/// </summary>
public string FileContentType
{get{return coFileContentType;}set{coFileContentType=value;}}
string coFileContentType;

/// <summary>
/// Initialize our class for use to send data files.
/// </summary>
/// <param name="url">The web address of the recipient of the data
transfer.</param>
public MultipartForm(string url)
{
URL = url;
coFormFields = new Hashtable();
ResponseText = new StringBuilder();
BufferSize = 1024 * 10;
BeginBoundary = "ou812--------------8c405ee4e38917c";
TransferHttpVersion = HttpVersion.Version11;
FileContentType = "text/xml";
}
//---------- BEGIN PROPERTIES SECTION ----------
string _BeginBoundary;
/// <summary>
/// The string that defines the begining boundary of
/// our multipart transfer as defined in the w3c specs.
/// This method also sets the Content and Ending
/// boundaries as defined by the w3c specs.
/// </summary>
public string BeginBoundary
{
get{return _BeginBoundary;}
set
{
_BeginBoundary =value;
ContentBoundary = "--" + BeginBoundary;
EndingBoundary = ContentBoundary + "--";
}
}
/// <summary>
/// The string that defines the content boundary of
/// our multipart transfer as defined in the w3c specs.
/// </summary>
protected string ContentBoundary
{get{return _ContentBoundary;}set{_ContentBoundary=value;}}
string _ContentBoundary;
/// <summary>
/// The string that defines the ending boundary of
/// our multipart transfer as defined in the w3c specs.
/// </summary>
protected string EndingBoundary
{get{return _EndingBoundary;}set{_EndingBoundary=value;}}
string _EndingBoundary;
/// <summary>
/// The data returned to us after the transfer is completed.
/// </summary>
public StringBuilder ResponseText
{get{return _ResponseText;}set{_ResponseText=value;}}
StringBuilder _ResponseText;
/// <summary>
/// The web address of the recipient of the transfer.
/// </summary>
public string URL
{get{return _URL;}set{_URL = value;}}
string _URL;
/// <summary>
/// Allows us to determine the size of the buffer used
/// to send a piece of the file at a time out the IO
/// stream. Defaults to 1024 * 10.
/// </summary>
public int BufferSize
{get{return _BufferSize;}set{_BufferSize = value;}}
int _BufferSize;
//---------- END PROPERTIES SECTION ----------
/// <summary>
/// Used to signal we want the output to go to a
/// text file verses being transfered to a URL.
/// </summary>
/// <param name="path"></param>
public void setFilename(string path)
{
coFileStream = new
System.IO.FileStream(path,FileMode.Create,FileAcce ss.Write);
}
/// <summary>
/// Allows you to add some additional field data to be
/// sent along with the transfer. This is usually used
/// for things like userid and password to validate the
/// transfer.
/// </summary>
/// <param name="key">The form field name</param>
/// <param name="str">The form field value</param>
public void setField(string key, string str)
{
coFormFields[key] = str;
}
/// <summary>
/// Determines if we have a file stream set, and returns either
/// the HttpWebRequest stream of the file.
/// </summary>
/// <returns></returns>
public virtual System.IO.Stream getStream()
{
System.IO.Stream io;
if( null == coFileStream )
io = coRequest.GetRequestStream();
else
io = coFileStream;
return io;
}
/// <summary>
/// Here we actually make the request to the web server and
/// retrieve it's response into a text buffer.
/// </summary>
public virtual void getResponse()
{
if( null == coFileStream )
{
System.IO.Stream io;
WebResponse oResponse;
try
{
oResponse = coRequest.GetResponse();
}
catch(WebException web )
{
oResponse = web.Response;
}
if( null != oResponse )
{
io = oResponse.GetResponseStream();
StreamReader sr = new StreamReader(io);
string str;
ResponseText.Length = 0;
while( (str = sr.ReadLine()) != null )
ResponseText.Append(str);
oResponse.Close();
}
else
throw new Exception("MultipartForm: Error retrieving server
response");
}
}
/// <summary>
/// Transmits a file to the web server stated in the
/// URL property. You may call this several times and it
/// will use the values previously set for fields and URL.
/// </summary>
/// <param name="aFilename">The full path of file being
transfered.</param>
public void sendFile(string aFilename)
{
// The live of this object is only good during
// this function. Used mainly to avoid passing
// around parameters to other functions.
coRequest = (HttpWebRequest) WebRequest.Create(URL);
// Set use HTTP 1.0 or 1.1.
coRequest.ProtocolVersion = TransferHttpVersion;
coRequest.Method = "POST";
coRequest.ContentType = "multipart/form-data; boundary=" +
BeginBoundary;
coRequest.Headers.Add("Cache-Control","no-cache");
coRequest.KeepAlive = true;
string strFields = getFormfields();
string strFileHdr = getFileheader(aFilename);
string strFileTlr = getFiletrailer();
FileInfo info = new FileInfo(aFilename);
coRequest.ContentLength = strFields.Length +
strFileHdr.Length +
strFileTlr.Length +
info.Length;
System.IO.Stream io;
io = getStream();
writeString(io,strFields);
writeString(io,strFileHdr);
this.writeFile(io, aFilename);
writeString(io,strFileTlr);
getResponse();
io.Close();
// End the life time of this request object.
coRequest = null;
}
/// <summary>
/// Mainly used to turn the string into a byte buffer and then
/// write it to our IO stream.
/// </summary>
/// <param name="io">The io stream for output.</param>
/// <param name="str">The data to write.</param>
public void writeString(System.IO.Stream io, string str)
{
byte[] PostData = System.Text.Encoding.ASCII.GetBytes(str);
io.Write(PostData,0,PostData.Length);
}
/// <summary>
/// Builds the proper format of the multipart data that
/// contains the form fields and their respective values.
/// </summary>
/// <returns>The data to send in the multipart upload.</returns>
public string getFormfields()
{
string str="";
IDictionaryEnumerator myEnumerator = coFormFields.GetEnumerator();
while ( myEnumerator.MoveNext() )
{
str += ContentBoundary + "\r\n" +
CONTENT_DISP + '"' + myEnumerator.Key + "\"\r\n\r\n" +
myEnumerator.Value + "\r\n";
}
return str;
}
/// <summary>
/// Returns the proper content information for the
/// file we are sending.
/// </summary>
/// <remarks>
/// Hits Patel reported a bug when used with ActiveFile.
/// Added semicolon after sendfile to resolve that issue.
/// Tested for compatibility with IIS 5.0 and Java.
/// </remarks>
/// <param name="aFilename"></param>
/// <returns></returns>
public string getFileheader(string aFilename)
{
return ContentBoundary + "\r\n" +
CONTENT_DISP +
"\"sendfile\"; filename=\"" +
Path.GetFileName(aFilename) + "\"\r\n" +
"Content-type: " + FileContentType + "\r\n\r\n";
}
/// <summary>
/// Creates the proper ending boundary for the multipart upload.
/// </summary>
/// <returns>The ending boundary.</returns>
public string getFiletrailer()
{
return "\r\n" + EndingBoundary;
}
/// <summary>
/// Reads in the file a chunck at a time then sends it to the
/// output stream.
/// </summary>
/// <param name="io">The io stream to write the file to.</param>
/// <param name="aFilename">The name of the file to transfer.</param>
public void writeFile(System.IO.Stream io, string aFilename)
{
FileStream readIn = new FileStream(aFilename, FileMode.Open,
FileAccess.Read);
readIn.Seek(0, SeekOrigin.Begin); // move to the start of the file
byte[] fileData = new byte[BufferSize];
int bytes;
while( (bytes = readIn.Read(fileData,0, BufferSize)) > 0 )
{
// read the file data and send a chunk at a time
io.Write(fileData,0,bytes);
}
readIn.Close();
}
}
}
"Fatih BOY" <fa***@smartcoding.org> wrote in message
news:On**************@TK2MSFTNGP11.phx.gbl...
Hi,
I want to send a report from a windows application to a web page like
'report.asp'

Currently i can send it via post method with a context like
local=En&Username=fatih&UserId=45&Firm=none
But the problem occures when i want to send a data with & sign (i.e:
Firm=F&B). I try to solve this problem with using boundary, but i failed.

Any idea!?

Fatih BOY

Nov 13 '05 #2
If I'm correct, you can use System.Web.HttpUtility.UrlEncode(string) to
encode your strings for proper url format. This converts all the 'strange'
characters to hexadecimal ascii values.

-ALD

"Fatih BOY" <fa***@smartcoding.org> wrote in message
news:On**************@TK2MSFTNGP11.phx.gbl...
Hi,
I want to send a report from a windows application to a web page like
'report.asp'

Currently i can send it via post method with a context like
local=En&Username=fatih&UserId=45&Firm=none
But the problem occures when i want to send a data with & sign (i.e:
Firm=F&B). I try to solve this problem with using boundary, but i failed.

Any idea!?

Fatih BOY

Nov 13 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: batista | last post by:
Hello All, my prob. is that i have a web server, and i want it to send fresh data,whenver it is available(from sum other source), to a webpage. Now i used refresh, but i want to use an...
2
by: _mario.lat | last post by:
I'd like to get text of a webpageB that I reach by putting a login and a password in a webpageA. I mean: I'd like to get text of a WebPageB with a php script. But before I can see WebPageB I...
5
by: trig | last post by:
Please help! I am an ICT teacher at a secondary school and my year 12 (AS Level) group need to create a website where data can be sent from a form to a Microsoft Access database. I am trying...
2
by: ajaxcoder | last post by:
Hi In my project i had a login form and i am trying to send the username and password to the server for authentication using xmlHttpRequest. Hence i am using POST request but i am unable to send...
3
by: romcab | last post by:
Hi guys, Just want to ask how can I send data serially? I have here a sample code but I use sockets and tcpclient class but I'm wondering how to do it using serial cable.Any idea? Private...
5
sid0404
by: sid0404 | last post by:
Hi I am new to the visualstudio.net I am trying to develop an application which requires me to send data to a HTML webpage - http://patft.uspto.gov/netahtml/PTO/search-bool.html and the user...
0
by: icyfenix | last post by:
I'm a developer for my company and my job is to make things move faster and reduce overhead/labor dollars using software. We are in an all-Microsoft environment. The problem I am having is this:...
0
by: nidhisahu | last post by:
Hello All, i am open this URL( http://id.skootit.com/WorkspaceService/ListInvitations?actor=http://goku.id.skootit.com/) directly in browser with enter credential then its open and show...
1
by: Abdulrahman Ahm | last post by:
Hello, How can I use jquery's post method to send a variable to my servlet, I am using a java web application, so far I have something like this $(document).ready(function() { ...
1
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
0
by: veera ravala | last post by:
ServiceNow is a powerful cloud-based platform that offers a wide range of services to help organizations manage their workflows, operations, and IT services more efficiently. At its core, ServiceNow...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: mar23 | last post by:
Here's the situation. I have a form called frmDiceInventory with subform called subfrmDice. The subform's control source is linked to a query called qryDiceInventory. I've been trying to pick up the...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.