Web-Service invoke with JavaScript - java

I am developing my first Web-Service at the moment.
Client is developed with JavaScript.
My problem is that it did not work. I do not know what my problem is.
I think it is a mistake on the client site.
I tried it with an Java Web-Service Client and there it works.
Web-Service:
import javax.jws.*;
import javax.jws.soap.SOAPBinding;
#WebService(name="TicketWebService", targetNamespace = "http://my.org/ns/")
#SOAPBinding(style = SOAPBinding.Style.RPC)
public class TicketWebService {
#WebMethod(operationName="getContact")
public String getContact()
{
return "Hallo Hans!!!";
}
}
Publish on Server:
import javax.swing.JOptionPane;
import javax.xml.ws.Endpoint;
public class PublishWsOnServer
{
public static void main( String[] args )
{
Endpoint endpoint = Endpoint.publish( "http://localhost:8080/services",
new TicketWebService() );
JOptionPane.showMessageDialog( null, "Server beenden" );
endpoint.stop();
}
}
Client:
<html>
<head>
<title>Client</title>
<script language="JavaScript">
function HelloTo()
{
var endpoint = "http://localhost:8080/services";
var soapaction = "http://localhost:8080/services/getContact";
xmlHttp = getXMLHttp();
xmlHttp.open('POST', endpoint, true);
xmlHttp.setRequestHeader('Content-Type', 'text/xml;charset=utf-8');
xmlHttp.setRequestHeader('SOAPAction', soapaction);
xmlHttp.onreadystatechange = function() {
alert(xmlHttp.responseXML);
}
xmlHttp.send(request);
}
</script>
</head>
<body onLoad="HelloTo()" id="service">
Body in Client
</body>
</html>
The alert does not work...

I'm pretty new at JAX-WS but I think that maybe your problem is not in the client side. First of all, here you have a HelloWorld example that works fine, if you look into the code you will see that in the web service implementation the annotation WebService is defined as
#WebService(endpointInterface = "com.mkyong.ws.HelloWorld")
which is the full package of your "TicketWebService". Another difference is that the example defines an interface (marked with the #WebService annotation) and then implements it, including the #WebService also in the implementation. I don't think this is mandatory, but is a good practice to define the interface.

Related

Java Rest API client - GET method - Error 415

I am new to writing Java client for Restful API using Apache CXF.
On running below code I am getting error 415 returned which when I looked online shows as "unsupported media type". In order to fix it I changed the code to "target.request(MediaType.APPLICATION_XML)" from original target.request(). However this didn't fix the code.
What is the best way to debug this issue?
Thanks a lot in advance for your time.
Update: After discussion with the Rest API developer I came to know that I need to add a header "("Content-Type", "application/x-www-form-urlencoded");". but I am not sure how to add a header. Does anyone know how to add this header here?
package com.blackhawk.ivr.restAPI.client;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
public class BlissRestAPI {
public static final String BLISS_SERVICRE_URL = "http://x.x.x.x:9090/services";
public static void main(String[] args) {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(BLISS_SERVICRE_URL);
target = target.path("/cardmanagementservices/v3/card/status").queryParam("ani", "xxxxxxxxxx").queryParam("card.expiration", "xxxxxx").queryParam("card.number", "xxxxxxxxxxxxxxxx").queryParam("channel.id", "xyz");
Invocation.Builder builder = target.request(MediaType.APPLICATION_XML);
Response response = builder.get();
System.out.println(response.getStatus());
response.close();
client.close();
}
}
First you can change the media type as given below.
Client: MediaType.APPLICATION_XML
Rest: MediaType.APPLICATION_JSON
JAX-WS are Java standard to build web service. So you have used it here, As my knowledge it is easy to use axis 2 to this kind of web services and clients since there are more implementations of JAX-WS. So i will give you a solution using apache axis technology.
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import javax.xml.rpc.ParameterMode;
public class axisClient {
public static void main(String [] args) throws Exception {
String endpoint = "http://localhost:8090/archive_name/service_name.jws";
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress( new java.net.URL(endpoint) );
call.setOperationName( "service_method_name" );
call.addParameter("parameter_name", XMLType.XSD_STRING, ParameterMode.IN );
call.setReturnType( XMLType.XSD_STRING );
call.setProperty(Call.CHARACTER_SET_ENCODING, "UTF-8");
String jsonString = (String) call.invoke( new Object [] { "parameter_value"});
System.out.println("Got result : " + jsonString);
}
}
I got it working by using below code (got 200 status returned)
WebClient client = WebClient.create(BLISS_SERVICRE_URL);
client.path("/cardmanagementservices/v3/card/status").query("ani", "xxxxxxxxxx").query("card.expiration", "xxxxxx").query("card.number", "xxxxxxxxxxxxxx").query("channel.id", "xxxxx");
client.type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_XML);
client.header("Content-Type","application/x-www-form-urlencoded");
Response response = client.get();
System.out.println(response.getStatus());

Retrofit #GET - how to display request string?

I'm working on an Android application that uses Retrofit to create a restful client. In order to debug networks calls, I would like to display or dump the url that's actually being invoked. Is there a way to do this? I've included some code below which shows how the app currently using retrofit.
Client interface definition:
import retrofit.Callback;
import retrofit.http.Body;
import retrofit.http.GET;
import retrofit.http.Headers;
import retrofit.http.POST;
import retrofit.http.Path;
// etc...
public interface MyApiClient {
#Headers({
"Connection: close"
})
#GET("/{userId}/{itemId}/getCost.do")
public void get(#Path("userId") String userId, #Path("itemId") String userId, Callback<Score> callback);
//....etc
}
Service which uses generated client:
// etc...
import javax.inject.Inject;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
#Inject
MyApiClient myApiClient;
// etc...
myApiClient.getCost(myId, itemId, new Callback<Cost>() {
#Override
public void success(Cost cost, Response response) {
Log.d("Success: %s", String.valueOf(cost.cost));
if (cost.cost != -1) {
processFoundCost(cost);
} else {
processMissingCost(itemId);
}
stopTask();
}
#Override
public void failure(RetrofitError error) {
handleFailure(new CostFailedEvent(), null);
}
});
}
call.request().url(), where call is type of retrofit2.Call.
RetrofitError has a getUrl() method that returns the URL.
Also the Response has a getUrl() method as well within the callback.
That, and you can also specify the log level as per this question:
RestAdapter adapter = (new RestAdapter.Builder()).
//...
setLogLevel(LogLevel.FULL).setLog(new AndroidLog("YOUR_LOG_TAG"))
Although based on the docs, LogLevel.BASIC should do what you need.
BASIC
Log only the request method and URL and the response status code and execution time.
Yes, you can enable debug logging by calling setLogLevel() on your RestAdapter.
I typically set logging to LogLevel.FULL for debug builds like so:
RestAdapter adapter = builder.setEndpoint("example.com")
.setLogLevel(BuildConfig.DEBUG ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE)
.build();
This will automatically print out all of the information associated with your HTTP requests, including the URL you are hitting, the headers, and the body of both the request and the response.

Java endpoint - perl consumer web service

I've problem with calling java endpoint (code below) from perl client (activePerl 5.16).
Those code snippets are from book Java Web Services Up And Running
package ch01.ts;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
#WebService
#SOAPBinding(style=Style.RPC)
public interface TimeServer {
#WebMethod
String getTimeAsString();
#WebMethod
long getTimeAsElapsed();
}
package ch01.ts;
import java.util.Date;
import javax.jws.WebService;
#WebService(endpointInterface="ch01.ts.TimeServer")
public class TimeServerImpl implements TimeServer {
public String getTimeAsString() {
return new Date().toString();
}
public long getTimeAsElapsed() {
return new Date().getTime();
}
}
package ch01.ts;
import javax.xml.ws.Endpoint;
public class TimeServerPublisher {
public static void main(String[] args) {
Endpoint.publish("http://127.0.0.1:9876/ts", new TimeServerImpl());
}
}
And the perl consumer:
use SOAP::Lite;
my $url = 'http://127.0.0.1:9876/ts?wsdl';
my $service = SOAP::Lite->service($url);
print "\nCurrent time is: ",$service->getTimeAsString();
print "\nElapsed miliseconds from the epoch: ", $service->getTimeAsElapsed();
When I'm calling the web service I'm having this stack trace:
maj 04, 2013 10:21:40 AM com.sun.xml.internal.ws.transport.http.HttpAdapter$HttpToolkit handle
SEVERE: Couldn't create SOAP message. Expecting Envelope in namespace http://schemas.xmlsoap.org/soap/envelope/, but got http://schemas.xmlsoap.org/wsdl/soap/
com.sun.xml.internal.ws.protocol.soap.VersionMismatchException: Couldn't create SOAP message. Expecting Envelope in namespace http://schemas.xmlsoap.org/soap/envelope/, but got http://schemas.xmlsoap.org/wsdl/soap/
at com.sun.xml.internal.ws.encoding.StreamSOAPCodec.decode(Unknown Source)
I think that the soap version is the problem, above example is from 1.1, when I've change the client code to
my $service = SOAP::Lite->service($url)->soapversion('1.2');
then different error is throw
com.sun.xml.internal.ws.server.UnsupportedMediaException: Unsupported Content-Type: application/soap+xml; charset=utf-8 Supported ones are: [text/xml]
I need help with either dealing with envelope problem or content-type. I will be grateful for any directions, code and anything else that could help.
I am not quite sure of Perl->Soap API, But for first case where client version is 1.1 may be you need to mention namespace also somewhere.
May be like
server->setNamespace() //or
SOAP::Lite->service($url,"<namespace>"); //please search for perl web service client examples
And for second case(1.2) service is expecting text and your api sends soap encoding or something.
Refer http://www.herongyang.com/Web-Services/Perl-SOAP-1-2-Unsupported-Media-Type-application-soap.html
This may be helpful
my $client = SOAP::Lite->new()
->soapversion('1.2')
->envprefix('soap12')
->default_ns('http://xmlme.com/WebServices')
->on_action( sub {join '/', #_} )
->readable(true)
->proxy('http://www.xmlme.com/WSShakespeare.asmx');
and
http://www.herongyang.com/Web-Services/Perl-SOAP-1-2-Request-Differences-SOAP-1-1-and-1-2.html
Hope it helps

php webservice return array,but can't get the array from java client

I wrote a php web service. The function is as follows:
function get_device_info(){
$conn= mysql_connect("localhost", "admin", "123456") or die("Could not connect: " . mysql_error());
mysql_select_db('devices',$conn);
$sql="select id,description,hostname,status_rec_date,availability from host";
$query=mysql_query($sql);
while($myrow = mysql_fetch_array($result)){
$host_msg[$i]=$myrow;
$i++;
}
return $host_msg;
mysql_close($conn);
}
Then I wrote the soap client in java to call this web service.
import java.net.MalformedURLException;
import java.rmi.RemoteException;
import javax.xml.rpc.ServiceException;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
public class javasoapclient {
public static void main(String[] args) throws ServiceException, MalformedURLException, RemoteException {
String serviceUrl = "http://192.168.1.44/webservices/serverSoap.php";
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress(new java.net.URL(serviceUrl));
call.setOperationName("get_device_info");
String reVal = call.invoke(new Object[] {}).toString();
System.out.println(reVal);
}
}
It can't get the array. I am a new in PHP. Can anyone help?
Thanks in advanceļ¼
That is not how SOAP works. SOAP has a unique structure:
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Body xmlns:m="http://www.example.org/stock">
<m:GetStockPrice>
<m:StockName>IBM</m:StockName>
</m:GetStockPrice>
</soap:Body>
</soap:Envelope>
What you are returning is just a simple array.
In order to get this array in java, you better use HttpClient

Web Service testing

I made web services using JAX-WS. Now I want to test using a web browser, but I am getting an error. Can somebody explain me please help.
My Service class:
package another;
import javax.jws.WebService;
import javax.xml.ws.Endpoint;
#WebService(name = "WebService")
public class WebServiceTest {
public String sayHello(String name) {
return "Hello : " + name;
}
public static void main(String[] args) {
WebServiceTest server = new WebServiceTest();
Endpoint endpoint = Endpoint.publish(
"http://localhost:9191/webServiceTest", server);
}
}
I run this class as simple Java program.
And I can see the WSDL in my browser at http://localhost:9191/webServiceTest?wsdl.
And I am trying to call this using the URL http://localhost:9191/webServiceTest?sayHello?name=MKGandhi, but I am not getting any result.
What is wrong here?
I can't tell you why it is not possible to test it in browser.
But at least I can tell you how to test it from your code, cause your webservice works:
package another;
import javax.jws.WebService;
#WebService
public interface IWebServiceTest {
String sayHello(String name);
}
package another;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
public class Main {
public static void main(String[] args) throws Exception {
String url = "http://localhost:9191/webServiceTest?wsdl";
String namespace = "http://another/";
QName serviceQN = new QName(namespace, "WebServiceTestService");
Service service = Service.create(new URL(url), serviceQN);
String portName = "WebServicePort";
QName portQN = new QName(namespace, portName);
IWebServiceTest sample = service.getPort(portQN, IWebServiceTest.class);
String result = sample.sayHello("blabla");
System.out.println(result);
}
}
You try and test your webservice by using the url http://localhost:9191/webServiceTest?sayHello?name=MKGandhi
Just try this url http://localhost:9191/webServiceTest/sayHello?name=MKGandhi
it should work fine :)
in your url "http://localhost:9191/webServiceTest?sayHello?name=MKGandhi"
try changing the localhost by your ip address.
example : "http://198.251.234.45:9191/webServiceTest?sayHello?name=MKGandhi"

Categories