JBoss EAP 5.1 Server not using Windows Network Setting - web-services

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.

Related

call a classic asp page from a console application

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.

connection.getConnetion() returns 404 code on WebSphere7

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

BOBJ. RESTFull WebService API. Get list of Data Providers returns "404" message

I use RESTFull WebService API (BOBJ 4.1) to retrieve the information about the reports in the repository.
When I try to derive the list of data providers, it works file for most of the reports. However, for some of the reports I get back the "(404) not found" message. I appreciate that it's a valid response for reports which don't have any data providers, but I'm sure that the reports I get the 404 message for definitely have one or more data providers. I also don't expect it to be related to the permissions, because I don't get the "access denied" message and I can open the "problematic" reports using the Rich Client.
I use the following link:
http://{servername}:{port}/biprws/raylight/v1/documents/{reportID}/dataproviders
Has anyone experienced this kind of a problem before? Am I missing something?
I was having the same problem with some of the BO REST services (some of which went away after we rebooted our server).
You don't say which technology you're using to call the web services, but here's how you'd get the error information in a C# application.
In my C# app, below are the functions I use to call a GET & POST Business Objects 4.x REST service, and if something goes wrong, it attempts to read in the error message, so we get more than just "404 not found" or "503 Server error"...
To use these functions, you must've logged into BO and got a Login token.
protected string CallGETWebService(string URL, string token)
{
HttpWebRequest GETRequest = null;
try
{
GETRequest = (HttpWebRequest)WebRequest.Create(URL);
GETRequest.Method = "GET";
GETRequest.Accept = "application/xml";
GETRequest.Timeout = 3 * 60 * 1000; // Wait for upto 3 minutes
GETRequest.KeepAlive = false;
GETRequest.Headers.Add("X-SAP-LogonToken", token);
HttpWebResponse GETResponse = (HttpWebResponse)GETRequest.GetResponse();
Stream GETResponseStream = GETResponse.GetResponseStream();
StreamReader reader = new StreamReader(GETResponseStream);
string response = reader.ReadToEnd();
return response;
}
catch (WebException ex)
{
// If the web service throws an exception, attempt to see if it give us any clues about what went wrong.
string exception = GetExceptionMessage(URL, ex);
throw new Exception(exception);
}
}
protected string CallPOSTWebService(string URL, string token, string XMLdata)
{
try
{
// Call a "POST" web service, passing it some XML, and expecting some XML back as a Response.
byte[] formData = UTF8Encoding.UTF8.GetBytes(XMLdata);
HttpWebRequest POSTRequest = (HttpWebRequest)WebRequest.Create(URL);
POSTRequest.Method = "POST";
POSTRequest.ContentType = "application/xml";
POSTRequest.Accept = "application/xml";
POSTRequest.Timeout = 3 * 60 * 1000; // Wait for upto 3 minutes
POSTRequest.KeepAlive = false;
POSTRequest.ContentLength = formData.Length;
POSTRequest.Headers.Add("X-SAP-LogonToken", token);
Stream POSTstream = POSTRequest.GetRequestStream();
POSTstream.Write(formData, 0, formData.Length);
HttpWebResponse POSTResponse = (HttpWebResponse)POSTRequest.GetResponse();
StreamReader reader = new StreamReader(POSTResponse.GetResponseStream(), Encoding.UTF8);
string response = reader.ReadToEnd();
return response;
}
catch (WebException ex)
{
// If the web service throws an exception, attempt to see if it give us any clues about what went wrong.
string exception = GetExceptionMessage(URL, ex);
throw new Exception(exception);
}
}
protected string GetExceptionMessage(string URL, WebException ex)
{
// If one of the BO web service threw an exception, attempt to see if it give us any clues about what went wrong.
string exception = "An exception occurred whilst calling: " + URL + ", " + ex.Message;
try
{
if (ex.Response == null)
return exception;
if (ex.Response.ContentLength == 0)
return exception;
using (Stream sr = ex.Response.GetResponseStream())
{
// The web service will return a string containing XML, which we need to parse, to obtain the actual error message.
StreamReader reader = new StreamReader(sr);
string XMLResponse = reader.ReadToEnd();
XElement XML = XElement.Parse(XMLResponse);
XElement XMLException = XML.Elements().Where(e => e.Name.LocalName == "message").FirstOrDefault();
if (XMLException != null)
exception = XMLException.Value; // eg "Info object with ID 132673 not found. (RWS 000012)"
}
}
catch
{
// If the web service returned some other kind of response, don't let it crash our Exception handler !
}
return exception;
}
The important thing here is that if BO's REST services fail, the GetResponse() will throw a WebException, and we then use my GetExceptionMessage() function to check the error response (which the BO Rest Services return in XML format) and try to extract the error message from it.
Using this functionality, our C# code can throw an exception with some useful information in it:
Info object with ID 132673 not found. (RWS 000012)
..rather than just throwing a vague exception like this (which, by the way, is what all of SAP's own C# examples will do, as none include any error-handling)...
(404) Page not found
(503) Service unavailable
I've also had cases where the BO REST Services will actually throw a "(503) Service Unavailable" exception... which was completely misleading ! Again, this code will help to give us the real error message.
If BO's REST services are successful, they'll return a string containing some XML data. Let's look at some sample code showing how we'd use my functions to call the REST service to get details about a particular Webi Report.
We'll call the REST services, then convert the XML response string into an XElement, so we can obtain the Report's name from the XML.
string token = /* Your login-token */
string URL = string.Format("http://MyServer:6405/biprws/infostore/{0}", ReportID);
string WebiReportResponse = CallGETWebService(URL, token);
// Parse the web service's XML response, and obtain the name of our Webi Report
XElement ReportDetails = XElement.Parse(WebiReportResponse);
XElement title = ReportDetails.Elements().Where(e => e.Name.LocalName == "title").FirstOrDefault();
string ReportName = (title == null) ? "Unknown" : title.Value;
I thoroughly loathe the SAP documentation (and lack of it).
Life would've been MUCH easier if SAP themselves had provided some sample .Net code like this...
I've regularly had this problem in a Java routine that trawls through all WebI reports in the system to find their data-providers. At the start of the routine it works OK but as time progresses it gets slower and throws up more and more of this kind of error. I'm fairly convinced that the program itself does nothing untoward to slow down the system and it calls other BO RESTful services with no problem.
In the end I went back to getting the information using the Java SDK and it works fine. It's also much faster than Restful, even when it's working normally. Using BO 4.1 SP7

why NotFound error occur in REST services with windows Phone app?

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.

Copy Web Service in SharePoint for Office 365

I am trying to upload files greater than 100 MB size to SharePoint Portal for Office 365. I have tried three different ways to achieve the same.
Copy Web Service, along with the httpRuntime Setting in place with maxRequestLength set as 2097151 and executionTimeout as 14400. Also, I did try setting the Timeout as "Infinite" and "60000".
Error: The underlying connection was closed: An unexpected error occurred on a send.
Web Client, using UploadDataAsync method to "PUT" the file bytes to the destination Url. Even with this, the httpRuntime setting was in place as above.
Error: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
HttpWebRequest, with ServicePointManager.Expect100Continue set to false. Also tried the same with SendChunked as both true and false.
Error: The request was aborted: The request was canceled.
Apart from all these, I have also added
protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
System.Net.HttpWebRequest webRequest =
(System.Net.HttpWebRequest) base.GetWebRequest(uri);
webRequest.KeepAlive = false;
return webRequest;
}
in the proxy class generated for Copy service. The limitation is I can't use CSOM to upload the files.
And still the Upload request times out every time. Any help would be very much appreciated.
Thanks in advance.
Try using the following piece of code :-
WebRequest webRequest = WebRequest.Create(url);
HttpWebRequest request = (HttpWebRequest)webRequest;
request.CookieContainer = CookieContainer;
request.Method = "PUT";
request.KeepAlive = true;
request.Timeout = Timeout.Infinite;
byte[] buffer = new byte[1024];
using (Stream stream = request.GetRequestStream())
{
using (MemoryStream memoryStream = new MemoryStream(fileBytes))
{
memoryStream.Seek(0, SeekOrigin.Begin);
for (int i = memoryStream.Read(buffer, 0, buffer.Length); i > 0;
i = memoryStream.Read(buffer, 0, buffer.Length))
{
stream.Write(buffer, 0, i);
}
}
}
WebResponse response = request.GetResponse();
response.Close();
Have you tried to change the default maximum upload file size?
What version of SharePoint are you using?