Jersey client request to web-service - java

I`m trying to request to web-service by jersey client:
WebResource service = client.resource(UriBuilder.fromUri("http://localhost:8080/jersey-example-new/").build());
System.out.println(service.path("rs/").path("account/details/1").accept(MediaType.APPLICATION_JSON).get(String.class));
but I get:
GET http://localhost:8080/jersey-example-new/rs/account/details/1 returned a response status of 406 Not Acceptable
Please, note that url path http://localhost:8080/jersey-example-new/rs/account/details/1 works in browser. What is wrong with java client request?
the endpoint code:
#Path("account")
public class AccountDetailsService {
#GET
#Path("/details/{param}")
#Produces(MediaType.TEXT_PLAIN)
public Response getAccountDetails(#PathParam("param") String accountName) {
String output = "Account Name : " + accountName;
return Response.status(200).entity(output).build();
}
}

You should change
System.out.println(service.path("rs/").path("account/details/1").accept(MediaType.APPLICATION_JSON).get(String.class));
to
System.out.println(service.path("rs/").path("account/details/1").accept(MediaType.TEXT_PLAIN).get(String.class));
You are only producing TEXT_PLAIN, but you request the media-type APPLICATION_JSON (via accept header), this is why you get the response, that the request is not acceptable.

Related

Content type : "Application/Json" issue with retrofit 2.2 while calling cake php apis

My Api is accepting Content-Type application/json as headers. I set Header perfectly as mentioned in Retrofit Docs.
#Headers("Content-Type: application/json")
#POST("user/classes")
Call<playlist> addToPlaylist(#Body PlaylistParm parm);
I also tried by setting content type in authentication interceptor class:
public class AuthenticationInterceptor implements Interceptor {
private String authToken;
public AuthenticationInterceptor(String token) {
this.authToken = token;
}
#Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder builder = original.newBuilder()
.addHeader("Content-type","application/json")
.addHeader("Authorization", authToken);
Request request = builder.build();
return chain.proceed(request);
}
}
But in Request Log it is Returning Content-Type txt/html.So how i should fix this issue? This api works fine in POSTMAN
I tried with all possible ways but it's not working with cake php web services.
Any help would be appreciated.

RestEasy client throwing exceptions

I have a REST service where in case of bad authorisation, I return 401 and some error message.
Example if I use postman or other rest client, the response status is 401 and payload:
{
"data": null,
"errors": [
{
"code": "REQUEST_NOT_AUTHORIZED",
"message": "Request not authorized"
}
]
}
If I use RestEasy client, then this exception is thrown automatically by the client:
EJB Invocation failed on component GatewayApi for method public com.example.AuthToken com.example.GatewayApi.authenticate(....): javax.ejb.EJBException: javax.ws.rs.NotAuthorizedException: HTTP 401 Unauthorized
Caused by: javax.ws.rs.NotAuthorizedException: HTTP 401 Unauthorized
If I try/catch the exception, then my payload is gone.
The way I am implementing is (for example):
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target(UriBuilder.fromPath(SERVICE_URL));
proxy = target.proxy(GatewayApiInterface.class);
Later edit - auth method
public AuthToken authenticate(String id, String name, String password) {
try {
ResponseEnvelope<AuthToken> authTokenResponseEnvelope = proxy.authenticate(id, name, password);
return authTokenResponseEnvelope.getData();
} catch (javax.ws.rs.NotAuthorizedException wae) {
return null;
}
}
Is any way to stop RestEasy throwing exception every time status != 200?
Or some way to obtain my original payload from the Rest Server?
Fixed it :). This is a small test example that I used. Before I was not using Response (my bad)
Server Side
#GET
#Path("/test")
public Response test() {
return Response.status(Response.Status.UNAUTHORIZED)
.entity("TEST")
.build();
}
Client Side Proxy Class
#GET
#Path("/test")
#Produces(MediaType.APPLICATION_JSON)
Response test();
Client
Response response = proxy.test();
String test = response.readEntity(String.class);
System.out.println(test);
System.out.println(response.getStatus());
response.close();

How to get MediaType.APPLICATION_JSON response using rest + jersey

I'm trying to do a simple rest client but I'm stuck trying to call a method which has as return type "MediaType.APPLICATION_JSON".
Basically I'm my java client I'm doing this:
private static String init(String password, String users) throws Exception {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(BASE_URI +MessageFormat.format("init/{0}/{1}", new Object[] {password,users}));
return target.request(MediaType.APPLICATION_JSON).get(String.class);
}
But I'm getting Error 404 when I'm doing the return

XMLHttpRequest and JAX-RS 404 403 errors, can't get a response from javascript

Java EE is hell. I'm trying to implement a RESt service that is going to be queried by clients from arbitrary domain, using javascipt XMLHttpRequest.
For the server side, my context root is "qwerty". Then my resource class is:
#Path("test")
public class TestRest{
#GET
#Path("/{msg}")
#Consumes("text/plain")
#Produces("text/plain")
public Response answerBackToClient(#PathParam("msg") String message){
Response.ResponseBuilder r;
r = Response.ok();
r = r.header("Access-Control-Allow-Origin", "*");
r = r.entity("responce back to client: " + message);
return r.build();
}
}
So from any browser anywhere now, with javascript:
var x = new XMLHttpRequest();
x.open("get", "http://www.pathtoserver.com:8080/qwerty/test/someMessage/", true);
x.setRequestHeader("Content-Type", "text/plain");
x.send("something");
Deployed on GlassFish4, EE7, NetBeans7.4
After i invoke the send() method on the client side (javascript), i get a 404 error or 403 error. What is the simplest possible example that will solve this problem?

Passing JSONObject in RestFul Webservice

I am using RestFul Webservice with JBoss Server to deploy the app to receive the JSONObject to my web service ,to test that i have created the web service and written test cases for it .Now i got hung up in passing the JSONobject from test case to web services , when i pass the json object to #post service calls it responses that Null Pointer Exception , even i have tried with passing string to it it responds null values.
I have used Annotations as follows in webservice
#consumes({Mediatype.APPLICATION_JSON})
#Consumes("application/json")
Test case As:
#Test
public void testgetmsg() {
String msg = "{\"patient\":[{\"id\":\"6\",\"title\":\"Test\"}]}";
try {
JSONObject obj = new JSONObject(new JSONTokener(msg));
WebResource resource = client.resource( "https://localhost:8443/../../resources/create");
ClientResponse response = resource.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).
entity(obj).post(ClientResponse.class,JSONObject.class);
}
}
can any body guide me to proceed further ?
Thanks in Advance
You don't need to create the json object, you can just pass the string.
you should
ClientResponse response = resource.type(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.post(ClientResponse.class, msg);
//CLIENT
public static void createStudent() {
String input = "{\"id\":12,\"firstName\":\"Fade To Black\",\"lastName\":\"Joy\"}";
ClientResponse response = service.path("class/post")
.type("application/json").post(ClientResponse.class, input);
System.out.println("Output from Server .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
System.out.println(response.getStatus()+ "OK");
}
Instead of using code client you can use add on firefox (POSTER) to passing value as json or formparam...
// create new student SERVER
//class
#POST
#Path("post")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response createStudent(Student st) {
// add new student
StudentDAO.instance.getModelStudent().put("8", st);
// response status code
return Response.status(200).entity(st).build();
}

Categories