Folks,
I am newbie to Java RESTful,
I need to pass the data from my java application to the RESTful service. I am able to add the RESTful to my application but not able to send any data back to the service.
I used #GET and #Consumes at service. Please help me to get connect and data exchange between the same
As RESTful acts as server in my application
RESTful defined
#GET
#Consumes("application/json")
#Path("{strID}")
public String getJson(#PathParam("strID")String strID){
return strID;
}
Imported RESTful method
public String getJson(String strID) throws UniformInterfaceException {
WebResource resource = webResource;
resource = resource.path(java.text.MessageFormat.format("{0}", new Object[]{strID}));
return resource.get(String.class);
}
inside the java application
static RESTful objRFIDService = new RESTful();
objRFIDService.getJson("RESTfultest");
What you are trying to achieve is not really clear. However, to consume a REST webservice, you can use the JAX-RS Client API, which is part of the JAX-RS 2.0 specification and the reference implementation is Jersey.
For instance, to perform a GET request to a resource available in http://example.com/api/foo/{id}, you can use the following code:
String id = ...
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://example.com").path("api").path("foo").path(id);
String result = target.request(MediaType.APPLICATION_JSON_TYPE).get(String.class);
For more details, have a look at the Jersey Client API documentation.
Related
I have a Java application that gets information on a general purpose channel.
I cannot listen on another port, and the application does not have(or implements) a webserver.
I want to activate some of the application's functionalities via REST API.
I already have the requested URI and parameters(of a single client request), but they are not in an HTTPRequest class.
How can I directly call the Spring REST API, using the data I have?
To illustrate what I want to do:
In myREST.java:
class myREST {
#RequestMapping(value = "/foos", method = RequestMethod.GET)
#ResponseBody
public List<Foo> getAllFoos {
return foos;
}
}
and in another file:
JSONObject restAPICaller(String uri, JSONObject params) {
JSONObject response = springRestAPI.call(uri, "GET", params);
return response;
}
where for instance, my uri is /foos/ , and params is {} (will have content for other examples)
How can I directly call the Spring REST API, using the data I have?
You cannot use an API via an HTTP client without an HTTP server.
I guess you can either:
Embed a server in your app and have it listen on some network port (you can bind to 127.0.0.1, so that the service is not accessible from other machines).
Directly call into the REST API classes (eg: new myREST(). getAllFoos())
Call into the business logic layer your API classes call into (iff you properly structured your code there)
I have been looking around for examples of how to call a Restful service written in Spring 3 from an EJB2 client. If i understand REST correctly, it should not matter what technology/language the service is written in so i should be able to call the service from an EJB2 client.
I couldn't find a simple example or reference to guide me on how to implement an EJB2 client that can call a restful service. Does this mean that is not possible to call a Restful service from an EJB2 client? If it is possible, could you please point me to a document or example that shows or describe how the two can interface/talk to each other.
Most of the references/documentation i come across are related to how to expose an EJB as a web service whereas i am interested in how to call a web service from an EJB2.
I am particularly interested in how i can send an XML document to the service. For example, is it possible to use a Jersey client and JAXB with EJB2 and how would i pass the unmarshalled XML over HTTP using EJB2?
Thanks in advance.
Below are a couple of programmatic options for accessing a RESTful service in Java.
Using JDK/JRE APIs
Below is an example of calling a RESTful service using the APIs in the JDK/JRE
String uri =
"http://localhost:8080/CustomerService/rest/customers/1";
URL url = new URL(uri);
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
JAXBContext jc = JAXBContext.newInstance(Customer.class);
InputStream xml = connection.getInputStream();
Customer customer =
(Customer) jc.createUnmarshaller().unmarshal(xml);
connection.disconnect();
Using Jersey APIs
Most JAX-RS implementations include APIs that make accessing RESTful services easier. A client API is being included in the JAX-RS 2 specification.
import java.util.List;
import javax.ws.rs.core.MediaType;
import org.example.Customer;
import com.sun.jersey.api.client.*;
public class JerseyClient {
public static void main(String[] args) {
Client client = Client.create();
WebResource resource = client.resource("http://localhost:8080/CustomerService/rest/customers");
// Get response as String
String string = resource.path("1")
.accept(MediaType.APPLICATION_XML)
.get(String.class);
System.out.println(string);
// Get response as Customer
Customer customer = resource.path("1")
.accept(MediaType.APPLICATION_XML)
.get(Customer.class);
System.out.println(customer.getLastName() + ", "+ customer.getFirstName());
// Get response as List<Customer>
List<Customer> customers = resource.path("findCustomersByCity/Any%20Town")
.accept(MediaType.APPLICATION_XML)
.get(new GenericType<List<Customer>>(){});
System.out.println(customers.size());
}
}
For More Information
http://blog.bdoughan.com/2010/08/creating-restful-web-service-part-55.html
I've built up a Webservice in Java using Jersey.
The Webservice consumes XML and takes a POJO (CoResponse) as MethodParameters.
I.E.
#PUT
#Consumes(MediaType.APPLICATION_XML)
public CoResponse test(CoResponse obj){
//...do something....
return obj;
}
On Client side I would do a Put Request like this...
CoResponse rO = service.path("path")
.type(MediaType.APPLICATION_XML_TYPE)
.accept(MediaType.APPLICATION_XML)
.put(CoResponse.class, new CoResponse());
Actually everything is working fine in our environment. But now I would like to know what the xml-string sent to the Server looks like. The reason why is to use the webservice also in other environments by creating a custom Serializer / Deserializer (i.e. for windows mobile) that is compatible to our jersey webservice.
Is there a way of looking into the put method to see the final xmlstring? Or some other possibilities?
Use a LoggingFilter.
Just add it to your client:
client.add(new LoggingFilter(System.out));
I have the following problem: I am completely new to java EE (know only about servlets and JSPs) and especially web services.
I need to develop a client for a web service (it needs to query the service for useful information once in a minute).
In my mind this client would be a simple java-SWing-based program, which would query the web service through simple Socket when the application client runs. How can that be done?
Is it possible to do in that way? If not, which is the easiest way to create such a client?
I would suggest using Apache CXF. Simple and powerful framework.
And yes, that is possible to implement what you said using this framework. Just read tutorials and play around for a bit with it.
Inorder to connect to a web service using a java client follow the below mentioned steps:
1. Get the URL in which the webservice is hosted. This is usually of the fomat http://<IP_OF_SERVER>:<PORT_OF_SERVER>/<WEB_APP_NAME>?wsdl
2. Get the qualified name of the service:
// 1st arg is the service URI
// 2nd is the service name published in the WSDL
QName qname = new QName(<Service_URI>, <SERVICE_NAME_PUBLISHED_WSDL>);<br/>
3. Create a factory for the service:
Service service = Service.create(url, qname);
4. Extract the endpoint interface, the service "port":
<Port_Class_Name> eif = service.getPort(<Port_Class_Name>);
5. Now use the methods on the Port, which are the actual methods in your webservice.
You might want to try REST Webservice, try Jersey REST (or others). With rest you can connect it with http connection (GET and POST).
Inorder to connect to a web service using a java client follow the below mentioned steps:
1.URL wsdlUrl = new URL("your wsdl url);
2.QName qname = new QName("targetNamespace in ur wsdl file","service name in your wsdl file");
Service service = Services.create(wsdlUrl,qname);
4.suppose getData() is your SEI
GetData data = (GetData)service.getPort(GetData.class);
5.call the your methods using data object
ex:data.getId(String name); this will return your response
I have a GWT client that would like to query a RESTful service that returns text/plain. I created a proxy interface:
public interface ConnectionStatusService extends ClientProxy
{
#Get("txt")
public void getVersion(Result<String> callback);
}
But when I'm using the generated proxy class:
ConnectionStatusService service = GWT.create(ConnectionStatusService.class);
it sends a request that accepts Accept application/x-java-serialized-object+gwt according to Firebug, so the server returns HTTP 406 Not Acceptable of course.. :-( How could I make it accept plain text?
I'm using resty-gwt to create restfull web services but I'm not accessing it now from GWT client classes. They have documentation where it's documented.
Hope that helps.