How to send a xml file over HTTP and HTTPS protocol and get result back - asp.net

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

Related

How to consume post/put WCF RestFul Service

I am doing crud operation(Using Stored Procedure) in wcf restful service .I have done with creating services,but How do I consume that service in my plain ASP.net Application(without Javascript,Jquery,AJAX). As I am new in WCF rest service.Plz give me step by step operation.
string sURL = #"http://localhost:50353/urUriName/"+ txtfname.Text;
WebRequest webGETURL;
webGETURL = WebRequest.Create(sURL);
webGETURL.Method = "DELETE";
webGETURL.ContentType = #"Application/Json; charset=utf-8";
HttpWebResponse wr = webGETURL.GetResponse() as HttpWebResponse;
Encoding enc=Encoding.GetEncoding("utf-8");
// read response stream from response object
StreamReader loResponseStream = new StreamReader(wr.GetResponseStream(), enc);
// read string from stream data
string strResult = loResponseStream.ReadToEnd();
// close the stream object
loResponseStream.Close();
// close the response object
wr.Close();
// assign the final result to text box
Response.Write(strResult);

How to call a WebService which has a querystring data?

I have a webservice which i need to call in .net application. The link looks like this.
http://www.contoso.com/student?id=12345
This will work only when its called like this. For rest of the this i dont have access. ie if i call it on a browser without the querystring it will not work. but with querystring it will return an XML data.
Now, when i call this in the .net application its not working?
How can I call this in a .NET application?
The Normal Webservice Importing methods are not working since it needs a querystring with value and we dont have access to the links which doesnt have the querystring.
How are you currently trying to download it?
A very simple way to do this is to use the HttpWebRequest and HttpWebResponse classes;
public XmlDocument GetStudentXml(int studentId)
{
XmlDocument targetXml = new XmlDocument();
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(String.Format("http://www.contoso.com/student?id={0}", studentId));
webRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
webRequest.Accept = "text/xml";
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
using (Stream responseStream = webResponse.GetResponseStream())
{
XmlTextReader reader = new XmlTextReader(responseStream);
targetXml.Load(reader);
reader.Close();
}
webResponse.Close();
return targetXml;
}
This method simply creates a HttpWebRequest, initializes it with the URL (via String.Format so as to append the student id), some windows credentials and the expected content type.
It then calls the remote address via the GetResponse method. The response is then loaded into a stream, and an XmlTextReader is used to load the Xml data from the response stream into the XmlDocument, which is then returned to the caller.
You can also use WebClient and XDocument to achieve the same thing:
string url = String.Format("http://www.contoso.com/student?id={0}", studentId);
string remoteXml;
using (var webClient = new WebClient())
{
remoteXml = webClient.DownloadString(url);
}
XDocument doc = XDocument.Parse(remoteXml);

The remote server returned an error: (400) Bad Request while consuming a WCF Service

Please view the code given below. While the debug reaches the request.GetResponse() statement the error has been thrown.
Uri uri = new Uri(address);
string data = "<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'><s:Body><HasRole xmlns='http://tempuri.org/'><userName>" + sid + "</userName><role>" + role + "</role></HasRole></s:Body></s:Envelope>";
data.Replace("'", "\"");
// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data);
if (uri.Scheme == Uri.UriSchemeHttps)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = "POST";// WebRequestMethods.Http.Post;
request.ContentLength = byteData.Length;
request.ContentType = "application/soap+xml; charset=UTF-8"; // "text/xml; charset=utf-8";
//request.ContentType = "application/x-www-form-urlencoded";
//Stream requestStream = request.GetRequestStream();
using (Stream writer = request.GetRequestStream())
{
writer.Write(byteData, 0, byteData.Length);
}
//writer.Close();
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
string tmp = reader.ReadToEnd();
Response.Close();
Response.Write(tmp);
}
I would double check the URL. If the URL looks ok on the client side, I recommend looking at access logs on your server to see what URL is being hit. 4xx errors mean a resource was not found. If the endpoint was correct, but the request was fubared, you would get a 5xx error code. (Assuming that your server side frameworks uses standard HTTP Response Codes).
As has been mentioned you should use the 'Add Service Reference' to access the WCF service from a .NET client. However, if you're emulating trying to connect from a non .NET client, your soap envelope is missing the header information.
<s:Header>
<Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">
specify your action namespace here (e.g. http://tempuri.org/ISomeService/Execute)
</Action>
</s:Header>

Unable to Pass Image in HTTP POST in a HTTP Web Request in ASP.NET

I am having trouble converting an image into bytes and saving it in database.
Here is the description,
I have an image that will be send from a remote device to the web server using HTTP POST.
so what I am doing is I ask them to sent the image to me.
Since the data is sent in POST i assume they will send me the Bytes by converting the bytes into string using
byte[] img = FileUpload1.FileBytes;
Encoding enc = Encoding.ASCII;
string img = enc.GetString(img);
Then they make a WebRequest using HTTPWebRequest and append this image in HTTP POST.
The Whole Code for making the request ---
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
//Create the POST Data
FileUpload img = (FileUpload)imgUpload;
Byte[] imgByte = null;
if (img.HasFile && img.PostedFile != null)
{
imgByte = imgUpload.FileBytes;
}
string imgPh = null;
Encoding enc = Encoding.ASCII;
if (imgByte != null)
{
imgPh = enc.GetString(imgByte);
}
string postData = "sid=8062BD53EB4552AD6D0FBB7E5DC5B7AF&status=Y&uid=123456789012&fname=Dinesh Singh&lname=Malik&ftname=Balwan&yrbirth=1988&gender=Male&address1=Address1&address2=Address2&address3=Address3&address4=Address4&imagePh=" + imgPh;
byte[] post = Encoding.UTF8.GetBytes(postData);
//Set the Content Type
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = post.Length;
Stream reqdataStream = request.GetRequestStream();
// Write the data to the request stream.
reqdataStream.Write(post, 0, post.Length);
reqdataStream.Close();
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
WebResponse response = null;
try
{
// Get the response.
response = request.GetResponse();
}
catch (Exception ex)
{
Response.Write("Error Occured.");
}
On the Page to which Request is made I am getting this image again into bytes using
Encoding enc = Encoding.ASCII;
byte[] imagePhoto = enc.GetBytes(postData["imageph"]);
From Here I save it into my Database
But when I retrieve the image using the Handler, it does not show the image.
The issue is the conversion of the image from byte[] to string and then converting string into byte[] at the Web Server. (Because when I save the image directly without this conversion using TestPage on server it shows the image.)
So What am I doing wrong in this.
Also is there any way in the above code to get the data of HTTP Post as received by the Web Server (retrieve HTTP Headers).
I want to retrieve this data received to sent it back to the Other Development to develop the request at the device in the same format as I am receiving in the HTTP Web Request URL
Any help would be appreciated.
Ok I think finally I figured it out.
What I did was -
Image -> byte[] -> Convert.ToBase64String -> Append The String Data to Post Request
At the Server-
Get the Post Data -> Convert.FromBase64String -> byte[] -> Insert into Database
Works Great...:)
Thanks

How to do httpPost to a webservice which accepts a byte array of a file using c#

I am working on an API kind of project,
I have wrote a WebMethod (not exactly. I am using MVC to create REST like API)
public UploadFileImage(string employeeId, byte[] imageBytes, string imageName)
{
// saves the imagebyte as an image to a folder
}
the web service would be consumed by a web app, or windows or even iphone or such portable stuffs. I am testing my web service using a web app, by simple httpPost.
string Post(Uri RequestUri, string Data)
{
try
{
HttpWebRequest request = HttpWebRequest.Create(RequestUri) as HttpWebRequest;
request.Method = "POST";
request.ContentType = IsXml.Checked ? "text/xml" : "application/x-www-form-urlencoded";
byte[] bytes = Encoding.ASCII.GetBytes(Data);
Stream os = null; // send the Post
request.ContentLength = bytes.Length; //Count bytes to send
os = request.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
HttpWebResponse httpWebResponse = (HttpWebResponse)request.GetResponse();
StreamReader streamReader = new StreamReader(request.GetResponse().GetResponseStream());
return streamReader.ReadToEnd();
}
catch (Exception ex)
{
return ex.Message;
}
}
This code works fine for evey method like, AddEmployee, DeleteEmployee etc. THe parameter Data is of form "Id=123&name=abcdefgh&desig=Developer",
How I call any other function is
Post(new Uri("http://localhost/addemployee"),"name=abcd&password=efgh")
where post is the function i wrote.
All good for all functions. Except that I dont know how to consume the above mentioned function UploadFileImage to upload an image?
Thanks
Try encoding the imageBytes as Base64.
From your code snippet is not too clear how you call UploadFileImage, that is how you convert its parameters tripplet into Data.
That is why my answer is quite generic:
In general, you'd better transfer your image file by
request.ContentType = "multipart/form-data; boundary=----------------------------" + DateTime.Now.Ticks.ToString("x");
Please allow me to refer you to a sample at StackOverflow on how to format a multipart request. I am sure that if you google, you shall find a lots of detailed examples and explanations as well.
I hope this helps :-)

Resources