System.Net.WebException: The request failed with HTTP status 400: Bad Request. calling a webservice dynamically - sql-server-2008

Iam calling a web service through my web service dynamically. I stored serviceName, MethodToCall, and array of parameters in my database table and execute these two methods to call a dynamic service url with .asmx extention and its method without adding its reference in my app. It works fine.
Following code is here.
public string ShowThirdParty(String strURL, String[] Params, String MethodToCall, String ServiceName)
{
String Result = String.Empty;
//Specify service Url without ?wsdl suffix.
//Reference urls for code help
///http://www.codeproject.com/KB/webservices/webservice_.aspx?msg=3197985#xx3197985xx
//http://www.codeproject.com/KB/cpp/CallWebServicesDynamic.aspx
//String WSUrl = "http://localhost/ThirdParty/WebService.asmx";
String WSUrl = strURL;
//Specify service name
String WSName = ServiceName;
//Specify method name to be called
String WSMethodName = MethodToCall;
//Parameters passed to the method
String[] WSMethodArguments = Params;
//WSMethodArguments[0] = "20500";
//Create and Call Service Wrapper
Object WSResults = CallWebService(WSUrl, WSName, WSMethodName, WSMethodArguments);
if (WSResults != null)
{
//Decode Results
if (WSResults is DataSet)
{
Result += ("Result: \r\n" + ((DataSet)WSResults).GetXml());
}
else if (WSResults is Boolean)
{
bool BooleanResult = (Boolean)WSResults;
if(BooleanResult)
Result += "Result: \r\n" + "Success";
else
Result += "Result: \r\n" + "Failure";
}
else if (WSResults.GetType().IsArray)
{
Object[] oa = (Object[])WSResults;
//Retrieve a property value withour reflection...
PropertyDescriptor descriptor1 = TypeDescriptor.GetProperties(oa[0]).Find("locationID", true);
foreach (Object oae in oa)
{
Result += ("Result: " + descriptor1.GetValue(oae).ToString() + "\r\n");
}
}
else
{
Result += ("Result: \r\n" + WSResults.ToString());
}
}
return Result;
}
public Object CallWebService(string webServiceAsmxUrl,
string serviceName, string methodName, string[] args)
{
try
{
System.Net.WebClient client = new System.Net.WebClient();
Uri objURI = new Uri(webServiceAsmxUrl);
//bool isProxy = client.Proxy.IsBypassed(objURI);
//objURI = client.Proxy.GetProxy(objURI);
//-Connect To the web service
// System.IO.Stream stream = client.OpenRead(webServiceAsmxUrl + "?wsdl");
string ccc = webServiceAsmxUrl + "?wsdl";// Connect To the web service System.IO.
//string wsdlContents = client.DownloadString(ccc);
string wsdlContents = client.DownloadString(ccc);
XmlDocument wsdlDoc = new XmlDocument();
wsdlDoc.InnerXml = wsdlContents;
System.Web.Services.Description.ServiceDescription description = System.Web.Services.Description.ServiceDescription.Read(new XmlNodeReader(wsdlDoc));
//Read the WSDL file describing a service.
// System.Web.Services.Description.ServiceDescription description = System.Web.Services.Description.ServiceDescription.Read(stream);
//Load the DOM
//--Initialize a service description importer.
ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
importer.ProtocolName = "Soap12"; //Use SOAP 1.2.
importer.AddServiceDescription(description, null, null);
//--Generate a proxy client.
importer.Style = ServiceDescriptionImportStyle.Client;
//--Generate properties to represent primitive values.
importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
//Initialize a Code-DOM tree into which we will import the service.
CodeNamespace codenamespace = new CodeNamespace();
CodeCompileUnit codeunit = new CodeCompileUnit();
codeunit.Namespaces.Add(codenamespace);
//Import the service into the Code-DOM tree.
//This creates proxy code that uses the service.
ServiceDescriptionImportWarnings warning = importer.Import(codenamespace, codeunit);
if (warning == 0)
{
//--Generate the proxy code
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
//--Compile the assembly proxy with the
// appropriate references
string[] assemblyReferences = new string[] {
"System.dll",
"System.Web.Services.dll",
"System.Web.dll",
"System.Xml.dll",
"System.Data.dll"};
//--Add parameters
CompilerParameters parms = new CompilerParameters(assemblyReferences);
parms.GenerateInMemory = true; //(Thanks for this line nikolas)
CompilerResults results = provider.CompileAssemblyFromDom(parms, codeunit);
//--Check For Errors
if (results.Errors.Count > 0)
{
foreach (CompilerError oops in results.Errors)
{
System.Diagnostics.Debug.WriteLine("========Compiler error============");
System.Diagnostics.Debug.WriteLine(oops.ErrorText);
}
throw new Exception("Compile Error Occured calling WebService.");
}
//--Finally, Invoke the web service method
Object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);
MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);
return mi.Invoke(wsvcClass, args);
}
else
{
return null;
}
}
catch (Exception ex)
{
throw ex;
}
}
Now the problem arraize when i have two different client servers. and calling a service from one server to the service deployed on other server. Follwing two kind of error log occurs. Cant find the exact reson for cope up this problem.
System.Net.WebException: The request failed with HTTP status 400: Bad Request.
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at MarkUsageHistoryInSTJH.InsertUpdateIssueItemAditionalDetail(String csvBarcode, String csvName, String csvPMGSRN, String csvGLN, String csvMobile, String csvPhone, String csvAddressLine1, String csvAddressLine2, String csvAddressLine3, String csvIsHospital)
and
System.Net.Sockets.SocketException (0x80004005):
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 172.17.13.7:80
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)

Please Carry Out Following Steps :
1) First of all try to access your service by adding reference of it.
It it works fine then we can say that there is no problem related to accessibility and permission.
2) If its not work then there is a problem with connection.
-->So Check Configuration in your service and try to set timeout for your web service.
(http://social.msdn.microsoft.com/Forums/vstudio/en-US/ed89ae3c-e5f8-401b-bcc7-
333579a9f0fe/webservice-client-timeout)
3)Now try after setting the timeout.
it operation completes successfully after above change that means now you can check with your web client method(dymamic calling).
4) If still problem persists then this might be network latency issue. Check the n/w latency between your client and server.
it will helps you.

Related

How to get gmail thread id using JavaMail API in android?

As per gimap documentation javamail new gimap doc, ImapMessage not casting to GmailMessage.
Doc code is:
GmailMessage gmsg = (GmailMessage)msg; System.out.println("Gmail message ID is " + gmsg.getMsgId()); String[] labels = gmsg.getLabels(); for (String s : labels) System.out.println("Gmail message label: " + s);
here msg is a object of ImapMessage.
Error is: java.lang.ClassCastException: com.sun.mail.imap.IMAPMessage cannot be cast to com.sun.mail.gimap.mailMessage
How to solve it?
My Imap connection code is:
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Folder;
String IMAP_PROTOCOL = "imap";
String IMAP_HOST = "imap.gmail.com";
String IMAP_PORT = "993";
private Store store;
private Folder folderInbox;
private Session session;
private Properties getServerProperties(String protocol, String host,
String port) {
Properties properties = new Properties();
// server setting
properties.put(String.format("mail.%s.host", protocol), host);
properties.put(String.format("mail.%s.port", protocol), port);
// SSL setting
properties.setProperty(
String.format("mail.%s.socketFactory.class", protocol),
"javax.net.ssl.SSLSocketFactory");
properties.setProperty(
String.format("mail.%s.socketFactory.fallback", protocol),
"false");
properties.setProperty(
String.format("mail.%s.socketFactory.port", protocol),
String.valueOf(port));
return properties;
}
//Now connect gmail with imap
Properties properties = getServerProperties(protocol, host, port);
session = Session.getDefaultInstance(properties);
store = session.getStore(protocol);
store.connect(userName, password);
// opens the inbox folder
folderInbox = store.getFolder(folderName);
folderInbox.open(Folder.READ_ONLY);
// fetches new messages from server
Message[] messages = folderInbox.getMessages();
for (Message msg: messages
) {
GmailMessage gmsg = (GmailMessage)msg;
System.out.println("Gmail message ID is " + gmsg.getMsgId());
String[] labels = gmsg.getLabels();
for (String s : labels)
System.out.println("Gmail message label: " + s);
}

Downloading file from mySQL DB via servlet hosted on AWS

I am currently creating a webpage that displays a table with data from an Mysql DB. One of the columns is a file (stored as a BLOB in the DB). The name of the file is an anchor tag that links to my download.java servlet. My download servlet works when deploying locally, however now that I have deployed to an AWS ElasticBeanstalk instance the servlet does not work.
In the log it says the following:
org.apache.coyote.http11.AbstractHttp11Processor.process Error parsing HTTP request header
Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level.
java.lang.IllegalArgumentException: Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986
and
/usr/share/tomcat8/Downloads/sdc.png (No such file or directory)
The servlet code:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "dbURL?serverTimezone=" + TimeZone.getDefault().getID();
Connection conn = DriverManager.getConnection(url , "username" , "password");
String fn = request.getParameter("Id");
String selectSQL = "SELECT file FROM Requests WHERE fileID=?";
PreparedStatement pstmt = conn.prepareStatement(selectSQL);
pstmt.setString(1, fn);
ResultSet rs = pstmt.executeQuery();
// write binary stream into file
String home = System.getProperty("user.home");
File file = new File(home+"/Downloads/" + fn);
FileOutputStream output = new FileOutputStream(file);
System.out.println("Writing to file " + file.getAbsolutePath());
while (rs.next()) {
InputStream input = rs.getBinaryStream("file");
byte[] buffer = new byte[1024];
while (input.read(buffer) > 0) {
output.write(buffer);
}
}
RequestDispatcher rd = request.getRequestDispatcher("/requests.jsp");
rd.forward(request, response);
rs.close();
pstmt.close();
} catch (SQLException | IOException e) {
System.out.println(e.getMessage());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The servlet should download the file from the Mysql DB to the users download folder. However, this only works locally, on the AWS server it fails. I assume this is because:
String home = System.getProperty("user.home");
returns the home path of the AWS server instance, rather than the path of the users/visitors home path.
Please help me adjust my servlet so that it works on the AWS server
UPDATE: After some research I think that getting the path to the client's download folder is not possible. Now I think I need to make us of a 'save as' dialog box. Any tips on how to do this and resources that could help me do this is appreciated
I was able to get my servlet working using code posted in a question here
My working code now looks like this:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection conn = null;
try {
// Get Database Connection.
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "dbURL?serverTimezone=" + TimeZone.getDefault().getID();
conn = DriverManager.getConnection(url , "username" , "password");
String fileName = request.getParameter("Id");
System.out.println("File Name: " + fileName);
// queries the database
String sql = "SELECT file FROM requests WHERE fileID= ?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, file);
ResultSet result = statement.executeQuery();
if (result.next()) {
// gets file name and file blob data
Blob blob = result.getBlob("file");
InputStream inputStream = blob.getBinaryStream();
int fileLength = inputStream.available();
System.out.println("fileLength = " + fileLength);
ServletContext context = getServletContext();
// sets MIME type for the file download
String mimeType = context.getMimeType(fileID);
if (mimeType == null) {
mimeType = "application/octet-stream";
}
// set content properties and header attributes for the response
response.setContentType(mimeType);
response.setContentLength(fileLength);
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", fileID);
response.setHeader(headerKey, headerValue);
// writes the file to the client
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[1024];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outStream.close();
}
else {
// no file found
response.getWriter().print("File not found for the fn: " + fileName);
}
} catch (Exception e) {
throw new ServletException(e);
}
}

Connecting SSIS WebService task to Spring WevService

I have a SSIS package in which i use a WebService task to call a Spring WS.
The authentication is done by client certificate and username & password.
I have tried to do it like this a simple HttpConnection and a WebService task - Error 504 Gateway Timeout. When i edit the HttpConnection and click on Test Connection i get an error that states:
"The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."
I have tried doing it with a script task and the same error.
I have even tried with a dummy console application and the same result.
I also have a java written app that actually does the job but i do not have access to it's code-behind. This basically proves that the problem is not from the server itself.
The java application has it's own keystore and the same certificates that i have installed on the server.
I opened a wireshark capture and i saw that when i used either of my apps the host made a DNS request for an address that i did not configure anywhere(it seems like a proxy address from the intranet), while the java app made a DNS request with the correct address.
I am stuck here, and i have no idea what the problem might be or what else i can do so that i would get a proper error.
Please advise!
Edit:
This is the code that calls the WS:
public static void CallWebService()
{
var _url = "https://<IP>/App/soap/DataService";
string action = "getData";
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("param1", "0");
parameters.Add("param2", "0");
parameters.Add("param3", "value");
XmlDocument soapEnvelopeXml = CreateSoapEnvelope(action, parameters);
HttpWebRequest webRequest = CreateWebRequest(_url);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
// begin async call to web request.
IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
// suspend this thread until call is complete. You might want to
// do something usefull here like update your UI.
asyncResult.AsyncWaitHandle.WaitOne();
// get the response from the completed web request.
string soapResult;
using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
{
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
}
Console.WriteLine(soapResult);
}
private static HttpWebRequest CreateWebRequest(string url)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
string thumbprint = "CERTIFICATE THUMBPRINT";
byte[] thumbprintArray = new byte[thumbprint.Split(new char[]{ ' ' }).Length];
string[] stringArray = thumbprint.Split(new char[] { ' ' });
for (int i = 0; i < thumbprintArray.Length; i++)
{
thumbprintArray[i] = Convert.ToByte(stringArray[i], 16);
}
X509Store localStore = new X509Store("My");
localStore.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certCol = localStore.Certificates.Find(X509FindType.FindByTimeValid, DateTime.Now, true);
foreach (X509Certificate cert in certCol)
{
if (cert.GetCertHashString() == thumbprint)
{
webRequest.ClientCertificates.Add(cert);
break;
}
}
webRequest.UseDefaultCredentials = false;
webRequest.Credentials = new NetworkCredential("USER", "PASSWORD");
return webRequest;
}
private static XmlDocument CreateSoapEnvelope(string action, Dictionary<string, string> parameters)
{
string formatedParameters = string.Empty;
string paramFormat = "<{0}>{1}</{0}>";
foreach (string key in parameters.Keys)
{
formatedParameters += string.Format(paramFormat, key, parameters[key]);
}
XmlDocument soapEnvelop = new XmlDocument();
soapEnvelop.LoadXml(string.Format(#"
<soapenv:Envelope xmlns:soap=""http://custom/soap/"" xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"">
<soapenv:Header/>
<soapenv:Body>
<soap:{0}>
{1}
</soap:{0}>
</soapenv:Body>
</soapenv:Envelope>", action, formatedParameters));
return soapEnvelop;
}
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}

Webservices object reference not set to an instance of an object error

I have to make a call to the web service (JSON) to authenticate the user who is trying to login to the app. I have the following xml provided
<summary>
http://geniewebsvc.cloudapp.net/Member.svc/Authenticate
</summary>
<param name="payload">
{"UserName":"testuser#somedomain.com","Password":"p#$$w0rd"}
</param>
<requiredHeaders>
Content-Type: application/json;charset=UTF-8
</requiredHeaders>
<returns></returns>
[OperationContract]
[WebInvoke(UriTemplate = "/Authenticate", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
AuthenticateResponse Authenticate(AuthCredentials usernamePassword);
There is similar one to check if the userid is already registered and that is a Get method. That works fine and i receive the right response for both successful and unsuccessful cases. But all the post methods are the ones which are giving me trouble. and i noticed that there is one more difference in these xmls.. i.e., the .. the isregistered webservice param tag goes something like this..
<param name="emailAddress"></param>
and here is my get() and post() please let me know whats my mistake...
public void Post()
{
RequestState myRequestState = new RequestState();
try
{
System.Uri uri = new Uri(url);
HttpWebRequest myHttpWebGetRequest;
Logger.log(TAG, "Create a HttpWebrequest object to the URL", url);
myHttpWebGetRequest = (HttpWebRequest)WebRequest.Create(uri);
_mHttpWebRequest = myHttpWebGetRequest;
myRequestState.conn = this;
myRequestState.request = myHttpWebGetRequest;
myRequestState.request.ContentType = "application/json;charset=UTF-8";
myRequestState.request.Method = "POST";
myRequestState.request.AllowReadStreamBuffering = false;
myRequestState.request.Headers["UserName"] = "rick.labarbera#gmail.com";
myRequestState.request.Headers["Password"] = "125124514";
// myRequestState.request.Headers["MemberId"] = "UdE8IwmTbxEjmzmMo2nBpg==";
IAsyncResult result = (IAsyncResult)myHttpWebGetRequest.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState);
}
catch (Exception e)
{
close(myRequestState);
if (this.listener != null)
{
Logger.log(TAG, "post()", e.Message);
}
}
}
public void Get()
{
RequestState myRequestState = new RequestState();
try
{
System.Uri uri = new Uri(url);
HttpWebRequest myHttpWebPostRequest;
Logger.log(TAG, "Create a HttpWebrequest object to the URL", url);
myHttpWebPostRequest = (HttpWebRequest)WebRequest.Create(uri);
_mHttpWebRequest = myHttpWebPostRequest;
myRequestState.conn = this;
myRequestState.request = myHttpWebPostRequest;
myRequestState.request.Method = "GET";
myRequestState.request.AllowReadStreamBuffering = false;
IAsyncResult result = (IAsyncResult)myHttpWebPostRequest.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState);
}
catch (Exception e)
{
close(myRequestState);
if (this.listener != null)
{
Logger.log(TAG, "get()", e.Message);
}
}
}
Am i doing something wrong???All these things are very very new to me.. I need help badly..
Thanks :)
I have played a bit with your code, but couldn't make it :(
What are the URL's you are using for the POST() method and for GET() methods.?
By the way, There is another way around to invoke your service. Follow these steps:
-- Create a new project.
-- Right-click on the Project name and click on "Add Service Reference"... Then provide address as "http://geniewebsvc.cloudapp.net/Member.svc" and click Go.
-- Once service information is downloaded, provide Namespace something like "MyMemberService" and click Ok.
Then Goto your MainPage.xaml.cs and write the following code.
MemberServiceClient client = new MemberServiceClient();
client.AuthenticateCompleted += new EventHandler<AuthenticateCompletedEventArgs>(client_AuthenticateCompleted);
client.AuthenticateAsync(new AuthCredentials() { UserName = "rick.labarbera#gmail.com", Password = "125124514" });
And the AuthenticateCompleted handler is
void client_AuthenticateCompleted(object sender, AuthenticateCompletedEventArgs e)
{
MessageBox.Show(e.Result.Successful.ToString());
}
This way you can simply call any service in the MemberService with just 2 or 3 lines of code. This is how a soap client is invoked in a Visual Studio project.
But again, there are some "Endpoint configuration" issues in this which you need to solve. And if you can do that you can save atleast 30 to 40 % of your development time.
Good luck.

Getting response status code 0 in SmartGWT webservice call using json

I have developed application using SmartGWT. Now I need to call webservice using json to another application which is deployed in another server for submitting username and password. When I make a request with url and POST method, getting the response status code as 0 and response text as blank.
Here is my code,
public void sendRequest() throws Exception {
// Get login json data to be sent to server.
String strData = createLoginReqPacket();
String url = "some url";
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
builder.setHeader("Content-Type", "application/json");
builder.setHeader("Content-Length", strData.length() + "");
Request response = builder.sendRequest(strData, new RequestCallback() {
#Override
public void onResponseReceived(Request request, Response response) {
int statusCode = response.getStatusCode();
System.out.println("Response code ----"+response.getStatusCode()+"");
if (statusCode == Response.SC_OK) {
String responseBody = response.getText();
System.out.println("Respose :" + responseBody);
// do something with the response
} else {
GWT.log("Response error at server side ----",null);
// do in case of server error
}
}// end of method.
#Override
public void onError(Request request, Throwable exception) {
GWT.log("**** Error in service call ******",null);
}// end of method.
});
builder.send();
}// end of send request.
Please anybody knows the solution?
as i am new to GWT/SmartGwt i don't no much about it.
#ModeEngage
There is no reason to use GWT class(RequestBuilder), But i don't have any idea to use Data source. Can u give reference or stuffs to do this??
And when i run this in chrome browser i get the following in error console.
XMLHttpRequest cannot load http:// "requested Url" . Origin http:// "localhost:8888" is not allowed by Access-Control-Allow-Origin.
Any solutions???
I believe this is caused by Firewall. I've run some test, and this is the most likely explanation.