Web service Error on retrieve a word document - asp.net

I get an error when trying to retrieve word document by webservice
HttpWebRequest request;
Uri uri = new Uri(serverUrl +
"/bare.aspx/" + Request.PathInfo);
request = (HttpWebRequest)WebRequest.CreateDefault(uri);
request.KeepAlive = false;
request.AllowAutoRedirect = false;
request.ReadWriteTimeout = -1;
request.Timeout = -1;
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.Method = "POST";
request.ContentType = "application/octet-stream";
// Serialize argument into request stream
Hashtable arguments = new Hashtable();
arguments["templateFile"] = templateFile;
arguments["hSetDataSource"] = hSetDataSource;
arguments["hSetRepeatBlock"] = hSetRepeatBlock;
arguments["messageForEmptyWord"] = messageForEmptyWord;
arguments["hImageBefore"] = hImageBefore;
arguments["hImageAfter"] = hImageAfter;
arguments["hImageInsideRepeater"] = hImageInsideRepeater;
MemoryStream buf = new MemoryStream();
BinaryFormatter fmt = new BinaryFormatter();
fmt.Serialize(buf, arguments);
request.ContentLength = buf.Length;
Stream reqStream = request.GetRequestStream();
buf.WriteTo(reqStream);
reqStream.Close();
buf.Close();
// Retreive word document from response and return it
// TODO: refactor this to stream directly into the response
HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
When I check the webservice response (HttpWebResponse resp), I get the following error:
System.Net.WebException: The remote server returned an error: (404) Not Found.
I don't understand where is the problem, thank you in advance for your help.

You are not hitting the endpoint. A 404 means the server could not find the URL you are requesting. Verify your .asmx URL by putting it in your web browser. If that works then make sure you code is using that same URL.

Related

How to pass value in url using web request GET method asp.net

Am new to .Net and web service..i like to pass id through url..how to do that?whether it was done post or get method?guide me
string url = "http://XXXXX//"+id=22;
WebRequest request = WebRequest.Create(url);
request.Proxy.Credentials = new NetworkCredential(xxxxx);
request.Credentials = CredentialCache.DefaultCredentials;
//add properties
request.Method = "GET";
request.ContentType = "application/json";
//convert
byte[] byteArray = Encoding.UTF8.GetBytes(data);
request.ContentLength = byteArray.Length;
//post data
Stream streamdata = request.GetRequestStream();
streamdata.Write(byteArray, 0, byteArray.Length);
streamdata.Close();
//response
WebResponse response = request.GetResponse();
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Clean up the streams and the response.
reader.Close();
response.Close();
If you just want to build the URL with parameters (ref: Query String) then you can simply do:
string url = string.Format("http://www.google.com/?id={0}",22);
You can check this url, Passing variables between pages using QueryString at Code Project

How to send authorized request

I send programatically a request to remote server:
string xml = "SomeXML Data";
string url = #"http://someserver.com";
WebRequest request = WebRequest.Create(url);
request.Method = "Post";
request.ContentType = "text/xml";
//The encoding might have to be chaged based on requirement
UTF8Encoding encoder = new UTF8Encoding();
byte[] data = encoder.GetBytes(xml); //postbody is plain string of xml
request.ContentLength = data.Length;
Stream reqStream = request.GetRequestStream();
reqStream.Write(data, 0, data.Length);
reqStream.Close();
System.Net.WebResponse response = request.GetResponse();
System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());
string str = reader.ReadToEnd();
but this code throws error:
The remote server returned an error: (401) Unauthorized.
I know user/pass to autorize when IE ask me.
Could anyone help me how to send authorized request?
Thanks!
webClient.Credentials = new NetworkCredential("Login", "Password");
Server seems to use Windows Authentication - although I am only guessing. If it is so, add this line:
request.Credentials = CredentialCache.DefaultCredentials;
looks like the server is using windows integrated security?
try something like this
WebRequest req = WebRequest.Create(tokenUri);
req.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
req.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;

Is it possible to use an asp.net page to have the get results from the server sent back as an XML file?

My application sending SMS request to Mblox XML interface through, I have get response from Mblox as XML file.
string RequestXML = GenerateRequestXML();
string uri = string.Empty; uri = "http://xml.us.mblox.com:8180/send";
HttpWebRequest request =(HttpWebRequest)WebRequest.Create(uri);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version11;
request.Method = "POST";
request.ContentType = "text/xml";
HttpWebResponse respon = (HttpWebResponse)request.GetResponse()
You are almost there... You already have your response, just get a reference to ResponseStream and read the XML returned:
HttpWebResponse respon = (HttpWebResponse)request.GetResponse();
Stream receiveStream = request.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader( receiveStream, encode );
//now you should be able to use readStream to get your XML. That's your homework.
See a complete example here

convert HTTP request code to HTTPS request code

I have got following code witch are sending xml file on HTTP protocol and getting response back as xml file from webserver and its working fine with HTTP protocol, but now i need to send such a XML file to HTTPS protocol (not http) and need to get response as xml file from it. the code to send xml file and get response from HTTP is :
string targetUri = "http://www.hostelspoint.com/xml/xml.php"; /*this will be like: "https://www.hostelspoint.com/xml/xml.php"*/
System.Xml.XmlDocument reqDoc = new System.Xml.XmlDocument();
reqDoc.Load(Server.MapPath("~\\getdetail.xml"));
string formParameterName = "OTA_request";
string xmlData = reqDoc.InnerXml;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUri);
string sendString = formParameterName + "=" + HttpUtility.UrlEncode(xmlData);
//string sendString = 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();
}
}
There shouldn't be much difference in your code, as HTTP or HTTPS differs only in transport level, not in application level.
What may become a problem here is, if the server certificate used in the targetUri is trusted on your server. In this case the HTTPS identity cannot be verified.

How to dynamically invoke Web Services in .Net

I am writing a Web service client in C# which takes the URL of the web Service, and a web method name.
I want to check if thew Web method actually receives an int and returns a DataTable, and if this is true, it should call it and return the DataTable.
I have found a couple of posts where this is accomplished compiling dynamically the Proxy class.
But for my case this'd be too expensive, because the client is actually a WSS WebPart, and I don't want to do this every time the page is rendered; only when the properties are changed.
In the end of the day web service description is just an XML file. You can grab it by requesting service.asmx?WSDL:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:1753/Service1.asmx?WSDL");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string xml = reader.ReadToEnd();
Once you have service description you can parse it and check method signature. Then, you can invoke the method using HTTP POST:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:1753/Service1.asmx?HelloWorld");
request.Method = "POST";
request.ContentType = "application/soap+xml; charset=utf-8";
byte[] data = Encoding.UTF8.GetBytes(
#"<?xml version='1.0' encoding='utf-8'?>
<soap12:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap12='http://www.w3.org/2003/05/soap-envelope'>
<soap12:Body>
<HelloWorld xmlns='http://tempuri.org/' />
</soap12:Body>
</soap12:Envelope>");
request.ContentLength = data.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string xml = reader.ReadToEnd();
If the Web Service is always the same (i.e. the method is the same as well as what it returns) and uit's just the url that might change, then just add a web reference to the project with the webpart in it, the set the Url of the proxy like so:
using (var serviceProxy = new ServiceProxy())
{
serviceProxy.Url = somepropertysetbythewebpart;
// make call to method here
}
After a lot of resarching I found out how to do it. The code of the selected answer is almost there, but I had to add the SOAPAction in the header and also change the ContentType.
Here is the entire code:
var strRequest = #"<soap12:Envelope>
...
</soap12:Envelope>";
string webServiceUrl = "http://localhost:8080/AccontService.svc";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webServiceUrl);
request.Method = "POST";
request.ContentType = "text/xml;charset=UTF-8";
request.Accept = "text/xml";
request.Headers.Add("SOAPAction", "http://tempuri.org/IAccountService/UpdateAccount");
byte[] data = Encoding.UTF8.GetBytes(strRequest);
request.ContentLength = data.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string responseXmlString = reader.ReadToEnd();
return new HttpResponseMessage()
{
Content = new StringContent(responseXmlString, Encoding.UTF8, "application/xml")
};

Resources