restful webservice with xml or json as parameter - java

I have a simple question the answer to which I have been trying to find out over the restricted internet connection in my office but to no avail.
1) How to create a restful web service in java preferably using netbeans that accepts xml and/or json as the parameter and how do I process it.
2) How do I call these web services. I mean how can we pass xml in the url?
Or is there any other way?
I would prefer using jersey if I have to use APIs.
I am sorry if the question is too generic, but I need all the knowledge I can get on this in relatively short time.

You can do this. I currently am working on webservices that do this.
Use these annotations:
#POST
#Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Object create(Object object);
On the objects you want to pass, you can annotation from the javax.xml.bind.annotation package. This way, java can marshal/unmarshal these itself.
#XmlRootElement(name = "Something")
#XmlAccessorType(XmlAccessType.NONE)
public class A {
private static final long serialVersionUID = 6478918140990163091L;
#XmlElementWrapper(name = "collectionWrapper")
#XmlElement(name = "collectionItem")
private final Collection<Object> domainCollection = new LinkedList<Object>();
}
To access it do something like this:
final Builder request = ClientBuilder.newClient().target(getBaseUri()).path("url").request(MediaType.APPLICATION_XML);
return request.post(Entity.entity(param, MediaType.APPLICATION_XML)).readEntity(A.class);
Follow this tutorial for examples: http://www.vogella.com/tutorials/REST/article.html

These are the general steps on how to do this (i assume you already have installed java and the corresponding environment variables):
1) Download and install Apache Tomcat. Configure Netbeans to identify the Apache Tomcat instance you have extracted/installed.
2) Download jersey jar files and add them to your Web Project from here (link: Jersey JAX-RS 2.0 RI bundle), or use the required dependencies if you are working with maven. Don't forget to add the project to the Apache Tomcat server.
3) Create a Jersey-based java class inside the source folder of your project. In each restful function you will define what data you will accept, how you will proccess them and what you will send. Here is a very basic example:
#Path("/server")
public class RestServer {
#POST
#Consumes(MediaType.TEXT_XML)
#Produces(MediaType.TEXT_XML)
public String basicPOSTRequest_XMLResponse(String xmlString) {
System.out.println("Received: " + xmlString);
return doSomethingWithString(xmlString);
}
}
4) Create an 'index.html' file in the webContent folder containing the corresponding ajax calls for your restful functions. (the ones you have created in the jersey class). In each ajax call, you will send and receive your data using jQuery functionality. Here is a basic ajax call example:
function ajaxCall(xmlData) {
$.ajax({
type: "POST",
url: _baseURI + "/server",
contentType: "text/xml",
data: xmlData,
datatype: "text/xml",
success:
function (data, textStatus, jqXHR){
alert(data);
},
error:
function (jqXHR, textStatus, errorThrown) {
alert("error");
}
});
}
Note that ajax is just one way to use your restful functions. For example you could do it with another java (or any other language) program that can send Http calls.
5) Start the tomcat server from eclipse.
6) Use your index.html file by hitting it's url (usually is something like: 'http://localhost:8080/-yourProjectName-') to check the restful functionality of your project.
The above are just guidelines. If you want more details in any step, tell it to me in order to edit my answer.

You can take reference to this link. And I hope that this link can be accessed from within your office.
Furthermore, accepting type of the parameter is a base for your requirement.
There are two annotations used for the accepting and responding type which are respectively #consume(MediaType) and #produce(MediaType). You will also have to specify the MediaType, like
MediaType.APPLICATION_JSON
or
MediaType.APPLICATION_XML_TYPE

Related

Quarkus: request to URL given as string

I want to make an HTTP request with Quarkus. However, the target URL is not known at compilation time, it will be composed from different parts at runtime.
Quarkus provides a way to build static REST clients like this:
#Path("/v2")
#RegisterRestClient
public interface CountriesService {
#GET
#Path("/name/{name}")
#Produces("application/json")
Set<Country> getByName(#PathParam String name);
}
However, I am loking for something like the Python requests package:
url = 'https://stackoverflow.com/questions/ask'
response = requests.get(url)
I am building the application in Kotlin, so all Java and Kotlin libraries should work.
What should I use?
With the MP REST Client defined in an interface, you can use the programmatic client creation API:
CountriesService remoteApi = RestClientBuilder.newBuilder()
.baseUri("created at runtime url")
.build(CountriesService.class);
remoteApi.getByName("");

Consuming a RESTful WebService passing a JSON object as request body

I've defined a RESTful WebService (by using RESTEasy on JBoss AS 7) that consumes a JSON data stream.
#PUT
#Path("/send")
#Consumes(MediaType.APPLICATION_JSON)
public Response consumeJSON(Student student) {
String output = student.toString();
// Do something...
return Response.status(200).entity(output).build();
}
How can I call my WS from another Spring-based webapp, by properly using the RestTemplate, mapping a Java Object to JSON and passing it as request body?
Note: I'm asking about Spring with the aim to investigate the facilities provided by the framework. I well know that it is possible to do that by defining manually the request body.
Cheers, V.
In the client application, you can create an interface with the same signature as the one you expose on the server side, and the same path.
Then, in the spring configuration file, you can use the RESTeasy client API to generate a proxy connecting to the exposed webservice.
In the client application, it would look like this :
SimpleClient.java
#PUT
#Path("/send")
#Consumes(MediaType.APPLICATION_JSON)
public Response consumeJSON(Student student);
Config.java
#Bean
public SimpleClient getSimpleClient(){
Client client = ClientFactory.newClient();
WebTarget target = client.target("http://example.com/base/uri");
ResteasyWebTarget rtarget = (ResteasyWebTarget)target;
SimpleClient simple = rtarget.proxy(SimpleClient.class);
return simple;
}
Then, in the place where you want to invoke this web service, you inject it with Spring and you can call the method. RESTeasy will search for the webservice matching with with your client (according to the path and the request type) and will create a connection.
Launcher.java
#Resource
private SimpleClient simpleClient;
public void sendMessage(Student student) {
simpleClient.consumeJSON(student);
}
Docs on the RESTesay client API : http://docs.jboss.org/resteasy/docs/3.0.7.Final/userguide/html/RESTEasy_Client_Framework.html
Hope this was helpfull.

How to change the response content type for a Dropwizard REST service?

I took a look at the Dropwizard framework and I want to use it to package my existing REST service.
In the tutorial I noticed that the response content type is not set using a ResponseBuilder, can I set the reponse type like I would do for a regular REST service if it were not in a Dropwizard framework ?
The reason I want to set a dynamic response content type is because the webservice does not know the kind of data it is serving.
Thanks
You should be able to just return a Response object and adjust the type. For instance:
#Path("/hello")
#Produces(MediaType.TEXT_PLAIN)
public class Example{
#GET
public Response sayHello() {
return Response.ok("Hello world").type(MediaType.TEXT_HTML).build();
}
}

Jersey: Is there a clean way to specify allowed URL extensions?

I'm using Jersey 1.17.1 and on every URL I've created I want to allow people to put ".json" at the end or not. Here's an example of what I've done:
#GET
#Path("basepath{extension: (\\.json)?}")
public String foobar() {
...
}
Eventually I'm going to let them choose between nothing, ".json" or ".xml" and I'm concerned about my DRY violation here. I'll have to change every #Path to this instead:
#GET
#Path("basepath{extension: (\\.json|\\.xml)?}")
public String foobar() {
...
}
Is there a better way to do this that lets my path value be more reusable? Although I can't use Jersey 2.0, I'd be interested to know if it can solve this problem.
One way to do this is to subclass PackagesResourceConfig and inform Jersey which extensions should map to which media types. For instance:
public class ExampleResourceConfig extends PackagesResourceConfig {
#Override
public Map<String, MediaType> getMediaTypeMappings() {
Map<String, MediaType> map = new HashMap<>();
map.put("xml", MediaType.APPLICATION_XML_TYPE);
map.put("json", MediaType.APPLICATION_JSON_TYPE);
return map;
}
}
and then your actual REST service might look like:
#GET
#Path("basepath")
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response foobar() {
...
}
Jersey will select the appropriate media type based on the url extension. Note that Response is returned instead of String. I'm not sure how you're building your response and what your requirements are but Jersey can handle converting your Java beans into either XML or JSON (or even JSONP) without a problem.
In the REST API implementation , the resource representation can be either xml or json or etc. This is not a good way of restful implementation if you specify the types as the extensions of the URL. The correct way is to use HTTP ACCEPT header
like Accept: application/json or
Accept: application/xml
Refer : http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html

How to test a versioned REST application with a vendor mime type?

I have a rest servlet using Jersey and I want to version it by using a vendor type. Here's the code:
#Path("/data")
public class UploadData {
#POST
#Path("/test")
#Consumes("application/vnd.blah.data-v1.0.0+xml")
public void addCustomerData(String xml) {
System.out.println("xml = " + xml);
}
}
I'm using a add-on to Chrome to test it (Simple Rest Client) but no matter what I do, I always get a "415 Unsupported Media Type" error returned.
Do I have to modify the headers of the client or is it something I can specify in the xml? I would like to still be able to use the Chrome add-on instead of a custom written client.

Categories

Resources