I need to call my .NET (C#) web service from a classic asp page. I want to test it by creating a console application that calls the asp page.
This is my asp page:
Dim strUserID
Dim strUserName
Dim strUserEmail
strUserID = Request.Form("UserID")
strUserName = Request.Form("UserName")
strUserEmail = Request.Form("UserEMail")
SET objSoapClient = Server.CreateObject("MSSOAP.SoapClient")
objSoapClient.ClientProperty("ServerHTTPRequest") = True
Call objSoapClient.mssoapinit("http://localhost:/MyWebService/Service1/" & _
"MyWebService.asmx?WSDL", "MyWebService")
strReturnValue = objSoapClient.SendData(strUserID, strUserName, strUserEmail)
response.Write("Returned from service with return value: " & strReturnValue)
Now my console application has to call the .asp page.
How do I construct the URL?
If the asp page is located in this folder: C:\Folder1\OldPage.asp, how do I construct the URL?
This is what I have so far:
static void Main(string[] args)
{
WebClient client = new WebClient();
Uri aspPagingServiceUri = new Uri("http://localhost/Folder1/OldPage.asp?UserID=g39s24&UserName=Gloria Test$UserEmail=gtest#hvhs.org");
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(aspPagingServiceUri);
httpWebRequest.Method = "GET";
var response = httpWebRequest.GetResponse();
HttpWebResponse resp = (HttpWebResponse)httpWebRequest.GetResponse();
Stream resStream = resp.GetResponseStream();
StreamReader reader = new StreamReader(resStream);
string strResponse = reader.ReadToEnd();
Console.WriteLine(strResponse);
reader.Close();
}
I get the error: 'The remote server returned an error: (503) Server Unavailable. ' when it gets to the GetResponse function.
I believe my problem is with the creation of the URL.
Thanks.
UPDATE
I have trying to connect to the ASP file that on the web server. I am getting a (500) error: "The remote server returned an error: (500) Internal Server Error."
The file is folder: C:\inetpub/wwwroot/Apps/Services/ServiceNew.asp
This is my console application:
static void Main(string[] args)
{
try
{
WebClient client = new WebClient();
Uri aspPagingServiceUri = new Uri("http://myserverName/Apps/Services/ServiceNew.asp?UserID=g39r345&UserName=John Smith&UserEmail=jsmith#mydomain.com&Subject=Test&MSG=Testing&ContactList=Sam Smith;");
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(aspPagingServiceUri);
httpWebRequest.Method = "GET";
var response = httpWebRequest.GetResponse();
HttpWebResponse resp = (HttpWebResponse)httpWebRequest.GetResponse();
Stream resStream = resp.GetResponseStream();
StreamReader reader = new StreamReader(resStream);
string strResponse = reader.ReadToEnd();
Console.WriteLine(strResponse);
reader.Close();
}
catch (WebException wex)
{
Console.WriteLine("Web Exception: " + wex.Message);
}
catch (Exception ex)
{
Console.WriteLine("General Exception: " + ex.Message);
}
}
The error is occurring var response = httpWebRequest.GetResponse();
Am I creating the URL correctly?
I am just following the file path.
You can not execute ASP code directly. What you need is to setup a web server that can execute classic ASP, i.e. Internet Information Services (IIS) on your machine, on another computer in a local network or externally.
IIS is part of some Windows distributions, you may just have to activate it. Make sure to install the classic ASP module, as this is not installed by default nowadays.
A warning: classic ASP often depends on additional COM components. So you may have to install more to get your code working.
Related
I have implemented a REST service using Spring Integration.
When I try to access the service manually using main function, It is working fine.
I also tested the service using REST Client in Google Chrome and that worked. But the service is coming back with responseCode 404 on WebSphere server. So I am facing the issue when I deploy the code on higher environment.
URL u = new URL("http://localhost:8080/MyApplication/testRestService");
URLConnection uc = u.openConnection();
HttpURLConnection connection = (HttpURLConnection) uc;
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept","*/*");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream out = connection.getOutputStream();
Writer wout = new OutputStreamWriter(out);
//helper function that gets a string from a dom Document
String input = jsonInput;
wout.write(input.getBytes());
wout.flush();
wout.close();
// Response
int responseCode = connection.getResponseCode();
Is is dependent on server, so its coming back with response code 404 ? Do we need any server side configuration ?
Any suggestion will be appreciated.
Why do you use different ContentType for URLConnection and for httpClient?
Show, please, your REST service config: 404 means Not found. Therefore you use (or don't) some options in request which makes it non-matching for the server's RequestMapping.
I tried with Apache HTTP Client and the code is working on WebSphere now. Still I am not able to find the reason why java.net.HttpURLConnection was not working on WebSphere.
Please find my updated code below :
DefaultHttpClient httpClient = null;
HttpPost postRequest = null;
StringEntity inputEntity = null;
HttpResponse response = null;
try{
//RETREIVE WEB SERVICE URL FROM DB
String callbackURL = "http://localhost:8080/MyApplication/testRestService";
httpClient = new DefaultHttpClient();
postRequest = new HttpPost(callbackURL);
String inputData = request.toString();
inputEntity = new StringEntity(inputData);
inputEntity.setContentType("application/x-www-form-urlencoded");
postRequest.setEntity(inputEntity);
response = httpClient.execute(postRequest);
if (response.getStatusLine().getStatusCode() != 201 && response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "+ response.getStatusLine().getStatusCode());
}
//System.out.println("HTTP Response Code :"+response.getStatusLine().getStatusCode());
LOGGER.debug("HTTP Response Code :"+response.getStatusLine().getStatusCode());
httpClient.getConnectionManager().shutdown();
}catch(IOException ex){
ex.printStackTrace();
throw ex;
}finally{
httpClient.getConnectionManager().shutdown();
httpClient = null;
postRequest = null;
inputEntity = null;
response = null;
}
I have installed web app server and now the server is 192.168.1.103 on IIS and i have a sample code from this site https://code.msdn.microsoft.com/office/Building-an-Office-Web-f98650d6/view/Discussions#content
in this sample the appwopiserver in web config is:
"wopihost.wingtip.com:8888/api/wopi/files/"
How can i create api/wopi/files/ directory in my server ? in other words i want to change this code to connect to my server .
here is the code that get the link:
public Link GetLink([FromUri] FileRequest fileRequest)
{
if (ModelState.IsValid)
{
var xml = WebConfigurationManager.AppSettings["appDiscoveryXml"];
var wopiServer = WebConfigurationManager.AppSettings["appWopiServer"];
bool updateEnabled = false;
bool.TryParse(WebConfigurationManager.AppSettings["updateEnabled"], out updateEnabled);
WopiAppHelper wopiHelper = new WopiAppHelper(HostingEnvironment.MapPath(xml), updateEnabled);
var result = wopiHelper.GetDocumentLink(wopiServer + fileRequest.name);
var rv = new Link
{
Url = result
};
return rv;
}
throw new ApplicationException("Invalid ModelState");
}
the final created link to open office in browser in this sample is:
http://owa1.wingtip.com/we/wordeditorframe.aspx?WOPISrc=http%3a%2f%2fwopihost.wingtip.com%3a8888%2fapi%2fwopi%2ffiles%2ftest.docx&access_token=YMDZjBxXlD4%3dlxnjDAq1aib0yGsNDo%2fd0Jm4b5R8eJircFrcaU84fgQ%3d
but i want something like this:
(http:// 192.168.1.103/we/wordeditorframe.aspx?WOPISrc=http%3a%2f%2fwopihost.wingtip.com%3a8888%2fapi%2fwopi%2ffiles%2ftest.docx&access_token=YMDZjBxXlD4%3dlxnjDAq1aib0yGsNDo%2fd0Jm4b5R8eJircFrcaU84fgQ%3d)
You have to replace App_Data\Discovery.xml with an XML you find at http://192.168.1.103/hosting/discovery (your OWA server).
I have an xml created from a SQL query through a stored procedure. I need to call a REST web service with that xml and get a response. I am using SQL Server 2008. Is there a way to do it from the stored procedure?
I keep seeing links to use SQL CLR to access the web service. In those links, I need to create a SQL Server project / .NET framework. I do not see those templates / options in my Visual Studio 2008 or SQL Server Management Studio.
Is there a way to call this https rest web service directly from the stored procedure?
===============
I am using the SQL CLR to do this. But somehow the xml is not getting passed right. I get a 500 error. Could you please see if there is anything wrong with this code.
public static void SampleWSPost(SqlString weburl, out SqlString returnval)
{
string url = Convert.ToString(weburl);
string feedData = string.Empty;
ASCIIEncoding encoding = new ASCIIEncoding();
try
{
HttpWebRequest request = null;
HttpWebResponse response = null;
Stream stream = null;
StreamReader streamReader = null;
XmlTextReader reader = new XmlTextReader("D:\\CXmls\\crmXml.xml");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(reader);
reader.Close();
request = (HttpWebRequest)WebRequest.Create(url);
CredentialCache mycache = new CredentialCache();
mycache.Add(new Uri(url), "Basic", new NetworkCredential("username", "password"));
request.Credentials = mycache;
request.Method = "POST";
request.ContentType = "text/xml";
string data = xmlDoc.InnerXml;
byte[] bytedata = Encoding.UTF8.GetBytes(data);
Stream newStream = request.GetRequestStream();
newStream.Write(bytedata, 0, bytedata.Length);
newStream.Close();
response = (HttpWebResponse)request.GetResponse();
stream = response.GetResponseStream();
streamReader = new StreamReader(stream);
feedData = streamReader.ReadToEnd();
response.Close();
stream.Dispose();
streamReader.Dispose();
}
catch (Exception ex)
{
SqlContext.Pipe.Send(ex.Message.ToString());
}
returnval = feedData;
}
i tried to connect REST web servie from windows phone 8 application.
it was working proberly for weeks but after no change in it I get this generic error :
System.Net.WebException: The remote server returned an error:
NotFound.
i tried to test it by online REST Clients and services works properly
i tried to handle Exception and parse it as webException by this code :
var we = ex.InnerException as WebException;
if (we != null)
{
var resp = we.Response as HttpWebResponse;
response.StatusCode = resp.StatusCode;
and i get no more information and final response code is : "NotFound"
any one have any idea about what may cause this error?
there is already a trusted Certificate implemented on the server . the one who has the server suggested to have a DNS entry for the server, this entry should be at the customer DNS or in the phone hosts file .that what i done and worked for awhile but now it doesn't work however i checked that there is no thing changed
this is sample for Get Request it works proberly on Windwos Store apps :
async Task<object> GetHttps(string uri, string parRequest, Type returnType, params string[] parameters)
{
try
{
string strRequest = ConstructRequest(parRequest, parameters);
string encodedRequest = HttpUtility.UrlEncode(strRequest);
string requestURL = BackEndURL + uri + encodedRequest;
HttpWebRequest request = HttpWebRequest.Create(new Uri(requestURL, UriKind.Absolute)) as HttpWebRequest;
request.Headers["applicationName"] = AppName;
request.Headers["applicationPassword"] = AppPassword;
if (AppVersion > 1)
request.Headers["applicationVersion"] = AppVersion.ToString();
request.Method = "GET";
request.CookieContainer = cookieContainer;
var factory = new TaskFactory();
var getResponseTask = factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
HttpWebResponse response = await getResponseTask as HttpWebResponse;
// string s = response.GetResponseStream().ToString();
if (response.StatusCode == HttpStatusCode.OK)
{
XmlSerializer serializer = new XmlSerializer(returnType);
object obj = serializer.Deserialize(response.GetResponseStream());
return obj;
}
else
{
var Instance = Activator.CreateInstance(returnType);
(Instance as ResponseBase).NetworkError = true;
(Instance as ResponseBase).StatusCode = response.StatusCode;
return Instance;
}
}
catch (Exception ex)
{
return HandleException(ex, returnType);
}
}
i tried to monitor connections from Emulator and i found this error in connection :
**
Authentication failed because the remote party has closed the
transport stream.
**
You saw the client implement a server side certificate in the service. Did you have that certificate installed on the phone? That can be the cause of the NotFound error. Please, can you try to navigate to the service in the phone or emulator internet explorer prior to testing the app? If you do that, you can see the service working in the emulator/phone internet explorer? Maybe at that point internet explorer ask you about installing the certificate and then you can open your app, and it works.
Also remember if you are testing this in the emulator, every time you close it, the state is lost so you need to repeat the operation of installing the certificate again.
Hope this helps.
If you plan to use SSL in production in general public application (not company-distribution app), you need to ensure your certificate has one of the following root authorities:
SSL root certificates for Windows Phone OS 7.1.
When we had same issue, we purchased SSL certificate from one of those providers and after installing it on server we were able to make HTTPS requests to our services with no problem.
If you have company-distribution app, you can use any certificate from company's Root CA.
I'm trying to call a web service from my application. My system is protected with a Firewall and I'm using a Proxy to access any external URL/internet access. The application is running on JBoss EAP 5.1 server. The application fails to write to the service URL with IO Exception: 'Could not transmit message'.
However, when I'm trying to access the service URL with IE/Firefox, it's opening. Although the XML response I'm receiving from Browser states a generic error - 'invalid request parameters...', which is quite obvious. Because I'm not sending a proper request XML from Browser.
I'm really confused with this disparity. I used to believe that JBoss will pick up standard windows network settings, but in my case it is not.
My code is as follows:
String strUrl = "http://theurlgoeshere";
String requestXml = "<request></request>";
String wsResponse="";
SOAPConnection conn = null;
try {
MessageFactory msgFac = MessageFactory.newInstance();
MimeHeaders mh = new MimeHeaders();
mh.setHeader("Content-Type", "text/xml; charset=UTF-8");
log.info("Request Xml:" + requestXml );
InputStream is = new ByteArrayInputStream(requestXml.getBytes("UTF-8"));
SOAPMessage reqMsg = msgFac.createMessage(mh, is);
SOAPConnectionFactory conFac = SOAPConnectionFactory.newInstance();
conn = conFac.createConnection();
SOAPMessage repMsg = conn.call(reqMsg, strUrl);
ByteArrayOutputStream out = new ByteArrayOutputStream();
repMsg.writeTo(out);
wsResponse = new String(out.toByteArray());
}
catch (Exception e) {
e.printStackTrace();
}
Got it sorted few days back. Basically I am using HttpURLConnection now to add proxy setting in the java code itself while making the Webservice call. Just closing this question, since my query is solved.
Will update the new code, if anyone needs.