What's the difference between using SoapUI and java code? - java

I'm using soap to request some information from server.
so, In order to test whether my soap way is the correct way or not, I tested soapUI Pro 4.6.3 program and java code.
when I use soapUI program , I got the response of my request from server. But, when I use java code I couldn't get response of my request from server..
I can see the error code 500. As I know, 500 Error code is Internal Error. so Isn't this problem of server?
I want to know what's the difference between them.
My java code is below.. and The XML code is the same what I use by SoapUI Program and what I use java code.
HttpClient client = new HttpClient();
PostMethod method = new PostMethod("My URL");
int status = 0;
String result = "";
try {
method.setRequestBody(MySoapXML);
method.getParams().setParameter("http.socket.timeout", new Integer(5000));
method.getParams().setParameter("http.protocol.content-charset", "UTF-8");
method.getParams().setParameter("SOAPAction", "My Soap Action URL");
method.getParams().setParameter("Content-Type", MySoapXML.length());
status = client.executeMethod(method);
BufferedReader br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
String readLine;
while ((readLine=br.readLine())!=null) {
System.out.println(readLine);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
method.releaseConnection();
}
and I already did URLConnection Class, and HttpClient Class.. but The result was the same..
If you know the way to solve this problem or have the same experience as me. please let me know how to solve this problem.. thank you for reading ^_^

Soap - UI will parse poorly defined webservices(for eg. Not Well Defined WSDL). From my experience working with SoapUI is not a proof that your webservice is well-defined.

Related

HTTP post request doesn't respond on production environment (war with tomcat server)

I have implemented a PerformHttpPostRequest function which is supposed to send a post request contains a JSON type body and get a JSON response via Apache HttpClient.
public static String PerformHttpPostRequest(String url, String requestBody) throws IOException {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(requestBody);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
CloseableHttpResponse response = client.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
InputStream is = httpEntity.getContent();
return (new BufferedReader(new InputStreamReader(is, "UTF-8"))).readLine();
}
The problem is, the code works perfect on developing environment, but when running the war file with a tomcat server but the request is not executed.
I've tried adding several catch blocks such as IOException, Exception and the code doesn't get there.
I've added debug prints which demonstrated that the code stops responding at the client.execute(...) command.
The function is called inside a try block, and after executing the .execute(...) command the code does get to the finally block.
I've already searched for a similar problem and didn't find an answer.
Is it a known issue? Does anyone have any idea of what can cause that? Or how can I fix it?
Hi Talor nice to meet you,
Please try to use HttpURLConnection to solve this issue like so:
Java - sending HTTP parameters via POST method easily
Have a nice day.
el profesor
I have tried with RestTemplate.
RequestObject requestObject = new RequestObject();
requestObject.setKey("abcd");
requestObject.setEndpoint(serviceEndPoint);
RestTemplate restTemplate = new RestTemplate();
HttpEntity<RequestObject> requestBody = new HttpEntity<RequestObject>(
requestObject);
ResponseEntity<RequestObject> result = restTemplate.postForEntity(
serviceEndPoint, requestBody, RequestObject.class);
Its very simple and hassle free, hope it helps
Few things you can try out.
- Try to do ping/curl from that box where you are running tomcat.
- Try to have a test method which make a get request to a server which is always reachable. For ex google.com and print the status. That way you could be able to know that you code is actually working or not in server env.
Hope this helps. :)
If the code doesn't pass beyond client.execute(...) but it does execute the finally block in the calling code, then you can find out what caused the aborted execution by adding this catch block to the try block that contains the finally:
catch(Throwable x) {
x.printStackTrace();
}
Throwable is the superclass for all exception and error classes, so catching a Throwable will catch everything.

Post with Java to PHP sending parameters and read parameters from PHP

I know that there are many questions related to this, but I have a special scenario and I'm here to know if somebody could help me with it, I have an approach to what is required, so let me describe the scenario first:
I have a PHP which is a kind of proxy, it will receives requests from some client, in my case a Java class using HttpUrlConnection. As soon as this PHP receives the connection (request), the php will extract the parameters sent by the client, in my case, the parameters are: an id (String) and an xml (as String). So, as soon as my java client sends the request, my php "proxy" catch it and extract the parameters, because my php is like an "intermediate" component which redirects the requests to another place using curl, but this specific php which receives the request needs to extract de id and the xml. From java, I am using:
URL calledUrl = new URL(phpUrl);
URLConnection phpConnection = calledUrl.openConnection();
HttpURLConnection httpBasedConnection = (HttpURLConnection) phpConnection;
httpBasedConnection.setRequestMethod("POST");
httpBasedConnection.setDoOutput(true);
StringBuffer paramsBuilder = new StringBuffer();
paramsBuilder.append("xmlQuery=");
paramsBuilder.append(URLEncoder.encode(this.xmlQuery, CHARSET));
paramsBuilder.append("&ids=");
paramsBuilder.append(URLEncoder.encode("16534", CHARSET));
PrintWriter requestWriter = new PrintWriter(httpBasedConnection.getOutputStream(), true);
requestWriter.print(paramsBuilder.toString());
requestWriter.close();
BufferedReader responseReader = new BufferedReader(new InputStreamReader(
phpConnection.getInputStream()));
String receivedLine;
StringBuffer responseAppender = new StringBuffer();
while ((receivedLine = responseReader.readLine()) != null ) {
responseAppender.append(receivedLine);
responseAppender.append("\n");
}
responseReader.close();
result = responseAppender.toString();
As you can see, I am sending the parameters and waiting for a response (which is an echo).
For my php, I have the following:
$rawdata = file_get_contents('php://input');
$rawXml = simplexml_load_file('php://input');
I don't know if this is ok, but I saw a tutorial about receiving requests and these lines were there. I want to get the data from the post that my java executes and then work with them as strings in my php.
If somebody could help me, I will really appreciate it. Thanks in advance, any help is welcome.
You would want to use this in PHP:
$id = $_POST['id'];
$xml = $_POST['xmlQuery'];

Apache httpclient: tutorial is broken - how to actually use this library?

I am using netbeans as an IDE to give you an indication of background.
I am playing around with the Apache httpclient library as in my current app I am having issues with the in built java HTTP connection.
I heard that the apache library was more powerful.
Anyway, the tutorial documentation that comes with the httpclient library on the apache site seems to be flawed:
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://localhost/");
HttpResponse response = httpclient.execute(httpget);
Net beans gives me issues with this code snippet (copied straight from the tutorial). Forget even the rudimentary URI of localhost, problems that arise with this are:
netbeans complains that HttpClient and DefaultHttpClient are incompatible types. The only way I can see around this is to cast with:
(HttpClient) new DefaultHttpClient();
Netbeans complains that the httpclient.execute() would throw an error because "httpget" here is simply a method and not a "HttpUriRequest".
How can a simple 3 line tutorial be so wrong and how would I actually successfully complete a request if there is so many flaws in this example?
I'm lost, can someone help. There seems to be several different ways, all not entirely what I'm looking for.
I want to be able to take a well-formed URL that I already have in the app in String, and then follow-all redirects. I'm not at all interested in the contents of the response, merely the cookies that it will drop.
Thanks,
Gregory
I suggest looking at your imports. I think NetBeans imported your HttpClient 3.x instead of 4.x. Try correcting your imports.
Have you tried using this code, they seem to use different mechanisms than you do. Taken from here. This is for the 3.X version though so it might be that you are using a different version.
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;
import java.io.*;
public class HttpClientTutorial {
private static String url = "http://www.apache.org/";
public static void main(String[] args) {
// Create an instance of HttpClient.
HttpClient client = new HttpClient();
// Create a method instance.
GetMethod method = new GetMethod(url);
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
try {
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
}
// Read the response body.
byte[] responseBody = method.getResponseBody();
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
System.out.println(new String(responseBody));
} catch (HttpException e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
} finally {
// Release the connection.
method.releaseConnection();
}
}
}
When I used this (on Android) I implemented a CustomHttpClient, following the example here

Calling webservice from java by posting the xml

I hope someone can help me. I'm a bit of a noob to Java. But I have a question regarding calling a web service from Java. The question is actually simple but one way works the other does not?
If I call a web service from Java like this, it works:
try {
String parameters = "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"+
"<soap:Body>"+
" <HelloWorld xmlns=\"http://np-challenger\" />"+
"</soap:Body>"+
"</soap:Envelope>";
//out.println(parameters);
java.net.URL url = new java.net.URL("http://localhost:50217/WebSite3/Service.asmx");
java.net.HttpURLConnection connjava = (java.net.HttpURLConnection)url.openConnection();
connjava.setRequestMethod("GET");
connjava.setRequestProperty("Content-Length", "" + Integer.toString(parameters.getBytes().length));
connjava.setRequestProperty("Content-Language", "en-US");
connjava.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
connjava.setRequestProperty("SOAPAction", "http://np-challenger/HelloWorld");
connjava.setDoInput(true);
connjava.setDoOutput(true);
connjava.setUseCaches(false);
connjava.setAllowUserInteraction(true);
java.io.DataOutputStream printout = new java.io.DataOutputStream (connjava.getOutputStream());
printout.writeBytes(parameters);
printout.flush();
printout.close();
java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(connjava.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
/*pagecontent += stuff;*/
}
in.close();
} catch (Exception e) {
System.out.println("Error: "+ e);
}
However, if I try to do it like this, I keep getting a bad request. I'm just about ready to pull my hair out.
try {
String xmlData = "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"+
"<soap:Body>"+
" <HelloWorld xmlns=\"http://np-challenger\" />"+
"</soap:Body>"+
"</soap:Envelope>";
//create socket
String hostname = "localhost";
int port = 50217;
InetAddress addr = InetAddress.getByName(hostname);
Socket sock = new Socket(addr,port);
FileWriter fstream = new FileWriter("out.txt");
// Send header
String path = "/WebSite3/Service.asmx";
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream(), "UTF8"));
bw.write("POST " + path + " HTTP/1.1\r\n");
bw.write("Host: localhost\r\n");
bw.write("Content-Type: text/xml; charset=\"utf-8\"\r\n");
bw.write("Content-Length: " + xmlData.length() + "\r\n");
bw.write("SOAPAction: \"http://np-challenger/HelloWorld\"");
bw.write("\r\n");
// Send POST data string
bw.write(xmlData);
bw.flush();
// Process the response from the Web Services
BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
bw.close();
br.close();
} catch(Exception e) {
System.err.println(e.getMessage());
e.printStackTrace(System.err);
}
I'm a bit suspicious whether the way you calculate the content length is correct, but more importantly:
Use a testing tool.
You can use a testing tool to compare between good and bad requests. One of such tools is soapUI, it's very convenient in showing you the exact contents of the requests and responses.
Create a new project in soapUI, based on the WSDL of your web service. Make sure to mark the checkboxes "Create sample requests for all operations" and "Create a Web Service Simulation of the imported WSDL". This way, soapUI will be able to act both as a client for your actual .NET web service, and as a server to which your Java client will connect.
Make sure that when soapUI connects acts as a client and connects to your web service, the request is processed correctly. Then run it as a server, send a request from Java, and compare it to the request that was processed successfully.
I chose to emphasize the role of a testing tool instead of addressing the specific problems in your code, because I believe that the ability to analyze the contents of your requests and responses will prove to be valuable time after time.
Use a WS framework.
Working with web services on such a low level requires a lot of unnecessary work from you. There are several frameworks and tools in Java that allow you to work on a higher abstraction level, eliminating the need to handle sockets and HTTP headers yourself. Take a look at the JAX-WS standard. This tutorial shows how to create a client for an existing web service. You'll notice that it's much simpler than your code sample.
Other popular WS frameworks in Java are Apache Axis2 and Apache CXF.
It's actually difference in data that is going to server. Monitor the data that you are actually posting using TCP Monitor. and compare the data i.e. mime header, request xml etc.
You will find the mistake. As far as I can see, first method is using GET method while second method is using POST method. I do not say that this is error just monitor actual data that is going to server and you will automatically get your problem resolved.

File not found exception while reading connection.getInputStream()

I am sending a request on a server URL but I am getting File not found exception but when I browse this file through a web browser it seems fine.
URL url = new URL(serverUrl);
connection = getSecureConnection(url);
// Connect to server
connection.connect();
// Send parameters to server
writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
writer.write(parseParameters(CoreConstants.ACTION_PREFIX + actionName, parameters));
writer.flush();
// Read server's response
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
when I try to getInputStream then it throws error file not found.
It is an .aspx Controller page.
If the request works fine in a browser but not in code, and you've verified that the URL is the same, then the problem probably has something to do with how you are sending your parameters to the server. Specifically, this part:
writer.write(parseParameters(CoreConstants.ACTION_PREFIX + actionName, parameters));
Perhaps there is a bug in the parseParameters() function?
But more generally, I would recommend using something a bit higher-level than a raw URLConnection. HtmlUnit and HttpClient are both fine choices, particularly since it seems like your request is a fairly simple one. I've used both to perform similar client/server interaction in a number of apps. I suggest revising your code to use one of these libraries, and then see if it still produces the error.
Ok finally I have found that the problem was at IIS side it has been resolved in .Net 4.0. for previous version go to your web.config and specify validateRequest==false

Categories

Resources