Environment: WildFly 8.1.
I deploy 2 applications on one server. One is connecting with other and trying to run POST method on rest service.
In service project I added:
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
#ApplicationPath("/rest")
public class RsActivator extends Application {
}
As far as I understand the user's guide for wildfly and jax-rs, this should be enough to run service listed below:
import javax.annotation.security.PermitAll;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import pl.patom.en.rest.model.LoginData;
import pl.patom.en.security.model.User;
import pl.patom.en.services.UserService;
#Path("services")
public class RestService {
#Inject
private UserService userService;
#PermitAll
#POST
#Consumes(MediaType.APPLICATION_JSON + ";charset=UTF-8")
#Path("/login")
public Response login(LoginData ld) {
User checkedUser = userService.findByLogin(ld.getUsername());
if (checkedUser == null || !checkedUser.getPassword().equals(ld.getPassword())) {
return Response.serverError().build();
}
return Response.ok().build();
}
}
In project where I call service I have this method:
public String login() {
try {
HttpClient client = HttpClientBuilder.create().build();
HttpPost postRequest = new HttpPost("http://localhost:8080/en/rest/services/login/");
LoginData ld = new LoginData(username, password);
Gson gson = new Gson();
String json = gson.toJson(ld);
StringEntity input = new StringEntity(json);
input.setContentType("application/json");
postRequest.setEntity(input);
postRequest.setHeader("Authorization", "Basic cm9vdDpyb290");
HttpResponse response = client.execute(postRequest);
if (response.getStatusLine().getStatusCode() == 200) {
loggedIn = true;
return "/secured/index.xhtml?faces-redirect=true";
} else {
loggedIn = false;
}
} catch (Exception e) {
loggedIn = false;
}
return null;
}
Why do I always get 200 OK response? It doesn't matter if I use #GET or #POST annotation = always OK. Secondly, ther is no debugger activity in method (application never stops on any breakpoint within this method):
public Response login(LoginData ld)
(It works when I use RESTClient in Firefox).
Oo, and there is another curious thing... In return with this 200 OK status I always get jsf login form.
Problem solved by adding: /rest/* to non-secured section of web-resource-collection.
Related
I am using some external API to GET and POST some ressources, locally my code works fine with the call of different endPoints (GET, POST...) and even with Postman, but when i try to run my code in another platerform (where the ressources are), i get the 412 HTTP error due to a POST call : after looking on the internet, i found out that i should generate an ETagd of the entity (that i went to modify) and add it into the header of my POST endPoint.
For that, i used ShallowEtagHeaderFilter and the #Bean annotation(above the filter method) and the #SpringBootApplication annotation above my class, here is my code :
package main.Runners;
import io.testproject.java.annotations.v2.Parameter;
import okhttp3.*;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.configurationprocessor.json.JSONArray;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.context.annotation.Bean;
import org.springframework.web.filter.ShallowEtagHeaderFilter;
import javax.servlet.Filter;
#SpringBootApplication
public class ActionRunner {
#Parameter(description = "the project ID")
public static String projectId = "xxx";
#Parameter(description = "the test ID")
public static String testId = "yyy";
public static void main(String[] args) throws Exception {
try {
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
Request request = new Request.Builder()
.url("https://api.testproject.io/v2/projects/"+projectId+"/tests/"+testId)
.method("GET", null)
.addHeader("Authorization", "nzmo4DI08ykizYgcp9-5cCTArlxq7k7zt9MYhGmTcRk1")
.build();
Response response = client.newCall(request).execute();
System.out.println("================ this is our response headers ::: \n"+ response.headers());
} catch(Exception e) {
System.out.println(e);
}
}
#Bean
public ShallowEtagHeaderFilter shallowEtagHeaderFilter(){
return new ShallowEtagHeaderFilter();
}
}
I really need Your help since i cant generate any ETag parameter on my GET response header(after checking reponse.headers() ).
Thanks in advance!
From this artcle, I have implemented calling another rest API from my REST API method in micronaut gradle application. Since my REST API expects jwt token I am sending the same token I received with in current request. I am seeing Unauthorized error even token is being passed. Can anyone help in this regard. Below is my code.
import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpStatus;
import io.appter.clientmgmt.models.ClientContact;
import io.appter.clientmgmt.repositories.IClientContactRepository;
import io.micronaut.http.uri.UriTemplate;
import io.micronaut.security.annotation.Secured;
import io.micronaut.security.authentication.Authentication;
import io.micronaut.security.rules.SecurityRule;
import io.micronaut.http.annotation.*;
import io.micronaut.http.client.RxHttpClient;
import io.micronaut.http.client.annotation.Client;
import io.reactivex.Flowable;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import javax.validation.constraints.NotNull;
import java.security.Security;
import java.util.List;
#Controller("/clientcontact")
//#Secured(SecurityRule.IS_ANONYMOUS)
public class ClientContactController {
private static final Logger LOG = LoggerFactory.getLogger(ClientContactController.class);
private IClientContactRepository clientContactRepository;
private final RxHttpClient httpClient;
public ClientContactController(IClientContactRepository clientContactRepository,
#Client("http://appterauthsvc-env.g2yapp2kcp.us-east-1.elasticbeanstalk.com") RxHttpClient httpClient) {
this.clientContactRepository = clientContactRepository;
this.httpClient = httpClient;
}
#Get("/")
public HttpStatus index() {
return HttpStatus.OK;
}
#Post("/")
#Secured(SecurityRule.IS_AUTHENTICATED)
public ClientContact createClientContact(#Body ClientContact clientContact,
Authentication authentication,
#Header("Authorization") String authorization) {
try {
List<ClientContact> existingClientContacts = clientContactRepository.getClientContactByClientId(clientContact.getClientId());
LOG.info("current contacts count for the client " + clientContact.getClientId() + " is " + existingClientContacts.size());
if (existingClientContacts.isEmpty()) {
User userObj = new User();
Long clientId = new Long(clientContact.getClientId());
userObj.setClientId(clientId);
userObj.setFirstName(clientContact.getFirstName());
userObj.setLastName(clientContact.getLastName());
userObj.setEmailId(clientContact.getEmailAddress());
userObj.setPhoneNo(clientContact.getContactNumber());
userObj.setIsActive(true);
LOG.info("User Email set is: "+userObj.getEmailId());
LOG.info("authorization token is: "+authorization);
HttpRequest<?> request = HttpRequest.POST("/user", userObj).bearerAuth(authorization);
String response = httpClient.toBlocking().retrieve(request);
LOG.info("Request Object: "+ request.toString());
LOG.info("Response Object: "+ response.toString());
LOG.info("User API executed.. ");
}
return clientContactRepository.createClientContact(clientContact);
} catch (Exception ex) {
LOG.error(ex.getMessage(), ex);
return null;
}
}
}
Thanks in advance.
Likely because #Header("Authorization") String authorization is returning something like Bearer xyz... and the bearerAuth method is adding Bearer to the string so you are sending Bearer Bearer xyz...
So just do .header(HttpHeaders.AUTHORIZATION, authorization)
Also as a side note you really shouldn't be doing blocking HTTP calls in this method. It's not the end of the world since in this case you're blocking an IO thread, however this type of code should be avoided.
If this has been asked somewhere before, please let me know. The crux of the problem may be similar, I'm not sure.
I basically have two programs on Eclipse. A client and a web service with rest (I'm using REST 3.1.3 by the way). The problem, quite simply, is that my client app is not linking to the restful web service to get the request I'm asking for.
Namely, I'm trying to get a list of author channels from the web service's own database. The problem is not that the service can't retrieve the data itself, rather than that the client can't access the web service to get THAT data from it and then display in its own JSP.
Here is the method from the client app that I'm trying to use:
#SuppressWarnings("unchecked")
#Override
public List<Channel> getAllChannels() {
Client client = ClientBuilder.newClient();
System.out.println("Client created.");
WebTarget target = client.target("http://localhost:8080/RESTService/examples/channels/authorchannels");
Response response = target.request().accept(MediaType.TEXT_PLAIN, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON).get();
List<Channel> channels = null;
if (response.getStatus() != 200) {
System.out.println("Could not retrieve!" );
} else {
channels = (List<Channel>) response.getEntity();
System.out.println(response.getMediaType().toString());
System.out.println(response.readEntity(String.class));
}
return channels;
}
It belongs to the following interface and class:
class Channel.java:
package examples.pubhub.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="channels")
public class Channel implements Serializable {
#Id
#Column(name="channel_user")
private String channel_user;
#Id
#Column(name="channel_bio")
private String channel_bio;
public Channel() {
}
public Channel(String user, String bio) {
super();
this.channel_user = user;
this.channel_bio = bio;
}
interface ChannelDAO.java :
package examples.pubhub.dao;
import java.util.List;
import examples.pubhub.model.Channel;
public interface ChannelDAO {
public List<Channel> getAllChannels();
public Channel getChannelByAuthorUser(String author_user);
public void createAuthorChannel(String author_user);
}
The method would send a get request to the following method in the web service:
AuthorChannel.java (from RESTService):
#GET
#Consumes({MediaType.TEXT_PLAIN, MediaType.APPLICATION_XML,
MediaType.APPLICATION_JSON})
#Path("authorchannels")
public List<Response> getAllChannels() {
Session session = DAOUtilities.getSessionFactory().openSession();
session.beginTransaction();
Query query = session.createQuery("from Channel");
#SuppressWarnings("unchecked")
List<Object> channels = query.list();
session.getTransaction().commit();
ResponseBuilder respBuilder = null;
if (channels == null)
respBuilder = Response.status(Response.Status.NOT_FOUND);
else
respBuilder = Response.status(Response.Status.OK);
respBuilder.entity(channels);
System.out.println("Channels? " + channels);
System.out.println("Users? " + ((Channel)
channels.get(0)).getChannel_user());
System.out.println("Bios? " + ((Channel)
channels.get(0)).getChannel_bio());
return (List<Response>) respBuilder.build();
}
When I try to test this on Postman, it gives me a 404. I'm not sure what's wrong. I'm thinking the URI might be incorrect, but I'm noticing conflicting theories on how the URI should be written.
My biggest problem is mostly misinformation on this topic; any help would be appreciated. If you want to see anything else from the code, please let me know.
Controller code:
package methods;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import org.hibernate.Query;
import org.hibernate.Session;
import model.Channel;
import resources.DAOUtilities;
#Path("/channels")
public class AuthorChannel {
#POST
#Path("/{id}")
#Consumes({MediaType.TEXT_PLAIN, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public void createAuthorChannel(#PathParam("id") String user, #QueryParam("bio") String bio) {
Session session = DAOUtilities.getSessionFactory().openSession();
Channel channel = new Channel();
channel.setChannel_bio(bio);
channel.setChannel_user(user);
session.save(channel);
session.flush();
session.getTransaction().commit();
}
#GET
#Consumes({MediaType.TEXT_PLAIN, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
#Path("/authorchannels")
public List<Response> getAllChannels() {
Session session = DAOUtilities.getSessionFactory().openSession();
session.beginTransaction();
Query query = session.createQuery("from Channel");
#SuppressWarnings("unchecked")
List<Object> channels = query.list();
session.getTransaction().commit();
ResponseBuilder respBuilder = null;
if (channels == null)
respBuilder = Response.status(Response.Status.NOT_FOUND);
else
respBuilder = Response.status(Response.Status.OK);
respBuilder.entity(channels);
System.out.println("Channels? " + channels);
System.out.println("Users? " + ((Channel) channels.get(0)).getChannel_user());
System.out.println("Bios? " + ((Channel) channels.get(0)).getChannel_bio());
return (List<Response>) respBuilder.build();
}
#GET
#Path("/{id}")
#Produces({MediaType.TEXT_PLAIN, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response getChannelByAuthorUser(#PathParam("id") String channel_user) {
Session session = DAOUtilities.getSessionFactory().openSession();
Query query = session.createQuery("from Channel where channel_user = :channel_user");
query.setParameter("channel_user", channel_user);
Channel channel = (Channel) query.uniqueResult();
session.getTransaction().commit();
ResponseBuilder respBuilder = null;
if (channel == null)
respBuilder = Response.status(Response.Status.NOT_FOUND);
else
respBuilder = Response.status(Response.Status.OK);
respBuilder.entity(channel);
return respBuilder.build();
}
}
I wasn't able to find out proper format how to send Response back to .JSP page after POST. First, how to obtain Response from Web service to Client?
Second question is how to call Client from Servlet.
Because second part is quite straightforward (create class instance in servlet in the proper doGet, doPost method), I will focus on the first question.
Snippet on the server side:
import java.math.BigInteger;
import java.util.List;
import java.util.logging.Logger;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.hibernate.SessionFactory;
// internal beans and classes
import com.deepam.util.BasicUtils;
import entities.CustomerRest;
import entities.DualInteger;
import entities.Dualloc;
import model.CustomerModel;
import model.DualModel;
import model.HibernateUtil;
#Path("/customer")
public class CustomerRestWS {
private final static Logger LOGGER = Logger.getLogger(CustomerRestWS.class.getName());
private CustomerModel cm = new CustomerModel();
private DualModel dm = new DualModel();
private final String CUSTSEQ = "customer_rest_seq";
SessionFactory sessionFactory;
/** Constructor
*/
public CustomerRestWS() {
super();
LOGGER.info("***" + LOGGER.getName());
sessionFactory = HibernateUtil.getSessionFactory();
}
...
#GET
#Path("/findcustseq")
#Produces(MediaType.APPLICATION_XML)
public DualInteger selectCustSeq() {
return cm.selectCustSeqNative(CUSTSEQ);
}
// post method how to save customer into DB
#POST
#Path("/create")
#Consumes(MediaType.APPLICATION_XML)
#Produces(MediaType.APPLICATION_JSON) // JSON is used for clearity between Consumes/Produces on the Client side
public Response create(final CustomerRest cust) throws JSONException {
Response response;
LOGGER.info("***" + LOGGER.getName() + " Insert Customer, id, name, last name: " + cust.getId() + ", " + cust.getFirstName() + ", " + cust.getLastName());
try {
cm.create(cust);
}
catch (Exception ex) {
// internal error
LOGGER.info("***" + LOGGER.getName() + " Exception: " + ex.getMessage());
response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(Response.Status.INTERNAL_SERVER_ERROR.toString()).build();
return response;
}
// created
response = Response.status(Response.Status.CREATED)
.entity(Response.Status.CREATED.toString()).build();
return response;
}
...
On the Client side:
import java.text.MessageFormat;
import java.util.logging.Logger;
import javax.ws.rs.core.MediaType;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.DefaultClientConfig;
// internal beans
import entities.Customer;
import entities.DualInteger;
import entities.ListCustomers;
public class CustomerRestfulClient {
private final static Logger LOGGER = Logger.getLogger(CustomerRestfulClient.class.getName());
private WebResource webresource;
private Client client;
private static final String BASE_URI = "http://localhost:8080/RestfulOracleServer/rest/";
public CustomerRestfulClient() {
// init client
client = Client.create(new DefaultClientConfig());
// init webresource
webresource = client.resource(BASE_URI).path("customer");
}
...
/** method getCustIdXML for obtaining unique ID (from sequence) */
public DualInteger getCustIdXML() throws UniformInterfaceException {
WebResource resource = webresource.path(MessageFormat.format("findcustseq", new Object[] {}));
return resource.accept(MediaType.APPLICATION_XML).get(DualInteger.class);
}
/** method saveCustXML call other method to obtain unique ID, than save Bean to DB */
public ClientResponse saveCustXML(String firstName, String lastName) throws UniformInterfaceException {
DualInteger custId = getCustIdXML();
LOGGER.info("Seqence number: " + (custId.getSeq()));
Customer cust = new Customer(custId.getSeq(), firstName, lastName);
ClientResponse response = webresource.path("create").
accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_XML).post(ClientResponse.class, cust);
LOGGER.info("Entity: " + response.getStatus());
return response;
}
Notice classes Response on the Server side and ClientResponse on the Client Side. Look how are treated #Consumes, #Produces annotations on server side to and accept, type methods on the Client side. There were my sources of errors.
In servlet Controller for .jsp simply create Client for WS e.g. custClient = new CustomerRestfulClient(); in constructor and use the obvious methods doGet, doPost as obvious. The Servlet has its own Request, Response different from Request, Response of WS. Be carefully in MVC model, Controller is treated by server as Singleton. In concurrent environment you must keep session continuity. (The most simple way is to use local variables in methods, when it is indicated.) Links to similar topics:
Is it ok by REST to return content after POST?
RESTful Java Client with POST method
I have a simple WS that is a #PUT and takes in an object
#Path("test")
public class Test {
#PUT
#Path("{nid}"}
#Consumes("application/xml")
#Produces({"application/xml", "application/json"})
public WolResponse callWol(#PathParam("nid") WolRequest nid) {
WolResponse response = new WolResponse();
response.setResult(result);
response.setMessage(nid.getId());
return response;
}
and my client side code is...
WebResource wr = client.resource(myurl);
WolResponse resp = wr.accept("application/xml").put(WolResponse.class, wolRequest);
I am trying to pass an instance of WolRequest into the #PUT Webservice. I am constantly getting 405 errors trying to do this..
How can I pass an object from the client to the server via Jersey ? Do I use a query param or the request ?
Both my POJOs (WolRequest and WolResponse) have the XMlRootElement tag defined so i can produce and consume xml..
I think the usage of the #PathParam is not correct here. A #PathParam is can basically be a String (see its javadoc for more info).
You can
use the #PathParam as a String parameter or
don't define WolRequest as a #PathParam.
The first approach:
#Path("test")
public class Test {
#PUT
#Path("{nid}")
#Consumes("application/xml")
#Produces({"application/xml", "application/json"})
public WolResponse callWol(#PathParam("nid") String nid) {
WolResponse response = new WolResponse();
response.setResult(result);
response.setMessage(nid);
return response;
}
This will accept urls like: "text/12", 12 will then be the String nid. It doesn't look like this will help what you are trying to do.
The second approach:
#Path("test")
public class Test {
#PUT
#Consumes("application/xml")
#Produces({"application/xml", "application/json"})
public WolResponse callWol(WolRequest nid) {
WolResponse response = new WolResponse();
response.setResult(result);
response.setMessage(nid.getId());
return response;
}
Your client code can be like you specified, only the url for PUT is: "test". Perhaps you need a combination of both one #PathParam for your id and one "normal" parameter to get your request data.
Check this link https://www.vogella.com/tutorials/REST/article.html
As per the code sample of method putTodo of class TodoResource ,
your code should be like this.
#Path("test")
public class Test{
#PUT
#Consumes("application/xml")
#Produces({"application/xml", "application/json"})
public WolResponse callWol(JAXBElement<WolRequest> nid) {
WolResponse response = new WolResponse();
response.setResult(result);
response.setMessage(nid.getValue().getId());
return response;
}
}
Hope this will solve your problem.
You can try something like this
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_XML)
#Produces(MediaType.APPLICATION_XML)
public Response callWol(WolRequest nid) {
WolResponse response = new WolResponse();
response.setResult(result);
response.setMessage(nid.getValue().getId());
return Response.status(Status.OK).entity(response).build();
}
You can try #PUT instead of #Post as well. Hope this helps
I had the same problem I solved in 3 Steps with Jackson in Netbeans/Glashfish btw.
1)Requirements :
some of the Jars I used :
commons-codec-1.10.jar
commons-logging-1.2.jar
log4j-1.2.17.jar
httpcore-4.4.4.jar
jackson-jaxrs-json-provider-2.6.4.jar
avalon-logkit-2.2.1.jar
javax.servlet-api-4.0.0-b01.jar
httpclient-4.5.1.jar
jackson-jaxrs-json-provider-2.6.4.jar
jackson-databind-2.7.0-rc1.jar
jackson-annotations-2.7.0-rc1.jar
jackson-core-2.7.0-rc1.jar
If I missed any of the jar above , you can download from Maven here http://mvnrepository.com/artifact/com.fasterxml.jackson.core
2)Java Class where you send your Post.
First ,Convert with Jackson the Entity User to Json and then send it to your Rest Class.
import com.fasterxml.jackson.databind.ObjectMapper;
import ht.gouv.mtptc.siiv.model.seguridad.Usuario;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.simple.JSONObject;
public class PostRest {
public static void main(String args[]) throws UnsupportedEncodingException, IOException {
// 1. create HttpClient
DefaultHttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost
= new HttpPost("http://localhost:8083/i360/rest/seguridad/obtenerEntidad");
String json = "";
Usuario u = new Usuario();
u.setId(99L);
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", u.getId());
// 4. convert JSONObject to JSON to String
//json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
//ObjectMapper mapper = new ObjectMapper();
//json = mapper.writeValueAsString(person);
ObjectMapper mapper = new ObjectMapper();
json = mapper.writeValueAsString(u);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json,"UTF-8");
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
//inputStream = httpResponse.getEntity().getContent();
}
}
3)Java Class Rest where you want to receive the Entity JPA/Hibernate .
Here with your MediaType.APPLICATION_JSON you recieve the Entity in this way :
""id":99,"usuarioPadre":null,"nickname":null,"clave":null,"nombre":null,"apellidos":null,"isLoginWeb":null,"isLoginMovil":null,"estado":null,"correoElectronico":null,"imagePerfil":null,"perfil":null,"urlCambioClave":null,"telefono":null,"celular":null,"isFree":null,"proyectoUsuarioList":null,"cuentaActiva":null,"keyUser":null,"isCambiaPassword":null,"videoList":null,"idSocial":null,"tipoSocial":null,"idPlanActivo":null,"cantidadMbContratado":null,"cantidadMbConsumido":null,"cuotaMb":null,"fechaInicio":null,"fechaFin":null}"
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.apache.log4j.Logger;
#Path("/seguridad")
public class SeguridadRest implements Serializable {
#POST
#Path("obtenerEntidad")
#Consumes(MediaType.APPLICATION_JSON)
public JSONArray obtenerEntidad(Usuario u) {
JSONArray array = new JSONArray();
LOG.fatal(">>>Finally this is my entity(JPA/Hibernate) which
will print the ID 99 as showed above :" + u.toString());
return array;//this is empty
}
..
Some tips : If you have problem with running the web after using this code may be because of the #Consumes in XML ... you must set it as #Consumes(MediaType.APPLICATION_JSON)
Try this it will work
Server Side:
#PUT
#Consumes(MediaType.APPLICATION_XML)
#Produces(MediaType.APPLICATION_XML)
public String addRecord(CustomClass mCustomClass)
{
///
///
///
return "Added successfully : "+CustomClass.getName();
}// addRecord
Client Side:
public static void main(String[] args)
{
///
///
///
CustomClass mCustomClass = new CustomClass();
Client client = ClientBuilder.newClient();
String strResult = client.target(REST_SERVICE_URL).request(MediaType.APPLICATION_XML).put(Entity.xml(mCustomClass), String.class);
}