i have a web service which contains a method like the following
[WebMethod]
public string UploadFile(byte[] bytes, string file_name)
{
}
i want to invoke this web service method using HttpWebRequest so that i can stream the file without buffering in memory. How can do it... i tried to invoke it as follows
HttpWebRequest hw = HttpWebRequest.Create("http://localhost/xxx/xxx.asmx/Upload") as HttpWebRequest;
hw.ContentType = "application/x-www-form-urlencoded";
hw.AllowWriteStreamBuffering = false;
hw.Method = "POST";
hw.UnsafeAuthenticatedConnectionSharing = true;
hw.UserAgent = "test type";
hw.Credentials = CredentialCache.DefaultCredentials;
FileInfo fi = new FileInfo("C:/Documents and Settings/Administrator/Desktop/a.txt");
string bytes = "bytes=";
byte[] by = UTF8Encoding.UTF8.GetBytes(bytes);
byte[] fn = UTF8Encoding.UTF8.GetBytes("&file_name=a.txt");
hw.ContentLength = by.Length+fi.Length+fn.Length;
using (Stream postStream = hw.GetRequestStream())
{
FileStream br = new FileStream("C:/Documents and Settings/Administrator/Desktop/a.txt", FileMode.Open, FileAccess.Read);
postStream.Write(by, 0, by.Length);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while (true)
{
bytesRead = br.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
break;
postStream.Write(buffer, 0, bytesRead);
}
br.Close();
postStream.Write(fn, 0, fn.Length);
postStream.Write(ct, 0, ct.Length);
}
// HERE :
using (HttpWebResponse response = hw.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string sssdd = reader.ReadToEnd();
}
but it show a message "The remote server returned an error: (500) Internal Server Error." while executing **// HERE : ** marked line.
btw: i am using asp.net 2.0 and i am not allowed to use proxy class as my requirement is to stream the data for large file. Thanks in advance
Open up http://localhost/xxx/xxx.asmx/Upload in your browser and ASP.NET will give you an example POST requrest you'll need to send in order to invoke the method. Start from there on.
It's been a while since I messed with this stuff, but I think you can get at the underlying HttpRequest in the proxy class. Probably alot easier than ginning up your own SOAP to POST.
If it says that the remote server returned an error, then you should look on the remote server to see what the error was. Look in the Event Log on the server for events at around the time you received the error.
Remove these lines:
postStream.Write(by, 0, by.Length);
.
.
.
postStream.Write(fn, 0, fn.Length);
postStream.Write(ct, 0, ct.Length);
Related
I am trying to upload files using Renci.SshNet, but the connection times out each time, although i can connect successfully using SFTP client (filezilla).
I have used the below code and each time I get exception in the line (sftp.Connect). I get an exception "An exception of type 'Renci.SshNet.Common.SshOperationTimeoutException' occurred in Renci.SshNet.dll"
{"Socket read operation has timed out"}
ConnectionInfo connectionInfo = new PasswordConnectionInfo(host, port, username, password);
using (var client = new SftpClient(host, port, username, password))
{
client.Connect();
//Log.Info("Connected to SFTP", this);
// byte[] byteArray = Encoding.UTF8.GetBytes(csv);
FileStream streams = File.OpenRead(#"c:\sftp\Test.csv");
byte[] fileBytes = new byte[streams.Length];
streams.Read(fileBytes, 0, fileBytes.Length);
MemoryStream stream = new MemoryStream(fileBytes);
using (var file = stream)
{
// sftp.BufferSize = 4 * 1024;
client.UploadFile(file, uploadFile + "/" + Path.GetFileName(path));
// Log.Info("Upload to SFTP success", this);
}
streams.Close();
client.Disconnect();
// Log.Info("Disconnected from SFTP", this);
}
I'm using Protobuf-net to try and send a serialized object to a webapplication that I'm running in another project. The Serializer.Serialize<T>() method takes a Stream (to write to) and and instance of T (in this case, a list of a few objects that I set up to work with protobuf-net)
How do I go about doing this? Do I need to write to a file or can I send the stream as postdata somehow? Below you can see I'm using a string as the postdata.
My execute post method
public static void ExecuteHttpWebPostRequest(Uri uri,string postdata, int requestTimeOut, ref string responseContent)
{
if (string.IsNullOrEmpty(uri.Host))// || !IsConnectedToInternet(uri))
return;
var httpWebReq = (HttpWebRequest)WebRequest.Create(uri);
var bytePostData = Encoding.UTF8.GetBytes(postdata);
httpWebReq.Timeout = requestTimeOut*1000;
httpWebReq.Method = "POST";
httpWebReq.ContentLength = bytePostData.Length;
//httpWebReq.ContentType = "text/xml;charset=utf-8";
httpWebReq.ContentType = "application/octet-stream";
//httpWebReq.TransferEncoding=
//httpWebReq.ContentType = "application/xml";
//httpWebReq.Accept = "application/xml";
var dataStream = httpWebReq.GetRequestStream();
dataStream.Write(bytePostData, 0, bytePostData.Length);
dataStream.Close();
var httpWebResponse = (HttpWebResponse)httpWebReq.GetResponse();
// Get the stream associated with the response.
var receiveStream = httpWebResponse.GetResponseStream();
// Pipes the stream to a higher level stream reader with the required encoding format.
var readStream = new StreamReader(receiveStream,Encoding.Default);
responseContent = readStream.ReadToEnd();
httpWebResponse.Close();
}
You can just serialize to the request:
Serializer.Serialize(dataStream, obj);
And equally, you can deserialize from receiveStream, if you choose.
Note, however, that protobuf data is not text, and should not be treated as such - very bad things happen if you try that.
I am trying to Bind my Outbound IP for my webRequest
HttpWebRequest reqhttp = (HttpWebRequest)req;
reqhttp.ServicePoint.BindIPEndPointDelegate = new System.Net.BindIPEndPoint(BindIPEndPointCallback);
reqhttp.Credentials = null;
reqhttp.AuthenticationLevel = AuthenticationLevel.None;
reqhttp.Method = "POST";
reqhttp.ContentLength = send.Length;
reqhttp.ContentType = "text/xml";
Stream dataStream = reqhttp.GetRequestStream();
dataStream.Write(send, 0, send.Length);
dataStream.Close();
public delegate IPEndPoint BindIPEndPoint(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount);
private IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
{
return new IPEndPoint(IPAddress.Parse("111.111.11.11"), 0); //bind to a specific ip address on your server
}
for some reason when i do this, it is throwing an error
if fails to execute this line
Stream dataStream = reqhttp.GetRequestStream();
An existing connection was forcibly closed by the remote host
i don't understand what is wrong in here.
Can any one help to understand whats wrong in this code and fix the issue.
The GetRequestStream() method will first trigger BindIPEndPointDelegat, then it will try to connect to the remote server. If you bind to a local end point that does not exists, or the remote server is unavailable, you will get an exception.
try something like this
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(myIP);
request.Proxy = myProxy;
ServicePoint sp = ServicePointManager.FindServicePoint(new Uri(myIP), myProxy);
sp.BindIpEndPointDelegate = new BindIpEndPoint(BindIpEndPointCallback);
HttpWebResponse = (HttpWebResponse)request.GetResponse();
I am calling WCF service from web application. It works fine for local webservice. When service deployed to dev server, it gives me above error. Webservice returns List of custom objects in xml format.
[OperationContract()]
[WebInvoke(Method = "POST", UriTemplate = "/track/get", ResponseFormat = WebMessageFormat.Xml)]
List<tokenCount> GetTracking(System.IO.Stream data);
If I return just a string from webservice, it works fine. Other operations in webservice work fine.
oRequest.ContentLength = aBytes.Length;
oRequest.KeepAlive = false;
oRequest.ProtocolVersion = HttpVersion.Version10;
oRequest.ConnectionGroupName = Guid.NewGuid().ToString();
oRequest.Timeout = 60000;
using (Stream oRequestStream = oRequest.GetRequestStream())
{
oRequestStream.Write(aBytes, 0, aBytes.Length);
using (HttpWebResponse oResponse = (HttpWebResponse)oRequest.GetResponse())
{
using (StreamReader oReader = new StreamReader(oResponse.GetResponseStream(), Encoding.UTF8))
{
Response.ContentType = "application/xml";
//resDoc = CreateMetaFile(oReader.ReadToEnd());
string r = oReader.ReadToEnd();
}
}
}
How many objects are you returning??
If that number gets high, you could run into two problems:
timeout: the server could take too long to get the answer ready and WCF will terminate the call
size: your size could exceed the settings for maxReceivedMessageSize on your client and thus be aborted
i want to send xml file with userid and password over HTTPs and then send all other xml file on HTTP using POST method and get the response as a xml file back. in ASP.NET (with vb.net preferred)
The url to which i want to send my xml file is:http://www.hostelspoint.com/xml/xml.php
exect xml file pettern is:
<?xml version="1.0" encoding="UTF-8"?>
<OTA_PingRQ xmlns="http://www.opentravel.org/OTA/2003/05"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.opentravel.org/OTA/2003/05OTA_PingRQ.xsd"
TimeStamp="2003-03-17T11:09:47-05:00"
Target="Production" Version="1.001" PrimaryLangID="en"
EchoToken="testtoken12">
<EchoData>Hello</EchoData>
</OTA_PingRQ>
You should check out the WCF REST Starter Kit, and watch the screencast on HTTP Plain XML (POX) Services which explains step by step how to do just that - create a WCF REST service that will accept and process a plain XML stream.
All the WCF and WCF REST screencasts by Pluralsight are highly recommended! It's excellent material on how to get started and work with WCF.
In addition to that, the MSDN WCF Developer Center is your first point of contact for any questions or more information on WCF and WCF REST.
i don't know why u removed correct answer from here but yesterday i got correct answer here. and it is:- (can any one tell me how to do same with HTTPS protocol?)
string targetUri = "http://www.hostelspoint.com/xml/xml.php";
System.Xml.XmlDocument reqDoc = new System.Xml.XmlDocument();
reqDoc.Load(Server.MapPath("~\\myfile.xml"));
string formParameterName = "OTA_request";
string xmlData = reqDoc.InnerXml;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUri);
string sendString = formParameterName + "=" + HttpUtility.UrlEncode(xmlData);
byte[] byteStream;
byteStream = System.Text.Encoding.UTF8.GetBytes(sendString);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteStream.LongLength;
using (Stream writer = request.GetRequestStream())
{
writer.Write(byteStream, 0, (int)request.ContentLength);
writer.Flush();
}
HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
string respStr = "";
if (request.HaveResponse)
{
if (resp.StatusCode == HttpStatusCode.OK || resp.StatusCode == HttpStatusCode.Accepted)
{
StreamReader respReader = new StreamReader(resp.GetResponseStream());
respStr = respReader.ReadToEnd(); // get the xml result in the string object
XmlDocument doc = new XmlDocument();
doc.LoadXml(respStr);
Label1.Text = doc.InnerXml.ToString();
}
}
Yes, you can do same thing using HTTPS protocol. You have to add this code before request:
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
bool validationResult = true;
//
// policy code here ...
//
return validationResult;
};