My object is info
info
Date: ""
ids: Array[1]
__proto__: Object
It has all the values and I send it in angular.
On the java side if the input parameter is like
public ResponseEntity<Boolean> update(#RequestBody myObject input) {...}
I get an error: 400 (Bad Request)
HTTP Status 400 -
type Status report
message
description The request sent by the client was syntactically incorrect.
But if in the api I do
public ResponseEntity<Boolean> update(#RequestBody String input) {...}
It works fine! what is wrong with it? myObject does have only
String Date;
String[] ids;
I'm assuming you're sending data from AngularJS using $http.post or $http.put? Angular sends JSON as a string in the request body. I would suggest you decode the JSON into a Java object using a library like Gson (see deserialization).
Related
I am using the framework in quarkus to build a rest client for the mandrill API
#RegisterRestClient
#Path("1.0")
#Produces("application/json")
#Consumes("application/json")
public interface MailService {
#POST
#Path("/messages/send-template.json")
JsonObject ping(JsonObject mandrillInput);
}
This is the relevant portion of my application.properties
com.example.service.MailService/mp-rest/url=https:/mandrillapp.com/api
And my example resource
#Path("/hello")
public class ExampleResource {
#Inject
#RestClient
MailService mailService;
#Produces(MediaType.TEXT_PLAIN)
#GET
public String hello() {
System.out.print("In the API");
JsonObject key = Json.createObjectBuilder().add("key", "ABCD").build();
System.out.println("The json built is "+key);
JsonObject response = mailService.ping(key);
System.out.println("The response is " + response);
return "hello";
}
}
What I saw is that if the API I am calling (Mandrill in this case) returns an error response (If my key is wrong for example), then the variable I am using to store the response doesnt get the response. Instead the REST API I am exposing to my application wrapping around this, gets populated with the response from Mandrill.
Is this expected behaviour? How can I debug the output of a rest client implementation in Quarkus?
The REST API being called is https://mandrillapp.com/api/docs/users.JSON.html#method=ping2
If you want to be able to get the body of the response when an error occurs, I suggest you use javax.ws.rs.core.Response as the response type.
You could also go another route and handle exceptions using ExceptionMapper
I need to send a value like app/role as parameter through rest webservice url from angularjs
In controller.js
var roleName = 'app/role';
checkRole.check({'roleName': roleName}, function(data){}
In model.js
popModel.factory('checkRole', function ($resource) {
return $resource('./rest/checkRole/:roleName',{roleName:'#roleName'},{
check: {'method':'GET'},
});
});
The rest webservice call in java
#GET
#Path("/checkRole/{roleName}")
#Produces(MediaType.APPLICATION_JSON)
public Response checkRole(#Context HttpServletRequest request, #PathParam("roleName") String roleName);
When i pass it i am getting browser console error as
Bad request response from the server.
For normal parameter values like 'Test', 'Solution', 'Application' etc. If i use with / as a parameter no process is done and i am getting error.
/ is reserved character for GET request. So, you can't use them directly. If you use them, you would get Bad Request Error.
One of the solution can be to encode the URL on client side and decode it on server.
Reference:
Characters allowed in GET parameter
How to handle special characters in url as parameter values?
I have a $http get method which should invoke my local server. I am getting proper response from my server through postman.
Following is my Json values:
[{"id":27885,"bslRef":acms.2016.04.00,"size":0,"isDefault":true,"baselineDate":null,"parentRef":null,"activities":null,"default":true,"open":true,"daily":false}]
As "bslRef":acms.2016.04.00 which is the value I am interested in is not enclosed in a json tag [""].
That is why i am getting an parsing error.
This is the error I am getting from jsonlint.
Error: Parse error on line 3:
...: 27885, "bslRef": acms .2016 .04 .00,
----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'
Following is my angularjs controller code:
$http.get('/baseline/getBaseline?', {params: {
currProject: $scope.selectedProject}})
.success(function(data) {
$scope.baselines=JSON.stringify(data);
})
.error(function(data) {
alert("failure");
});
I have tried with parse() method and stringify() method but of no use.
My server side application is a spring-mvc rest application, which is giving me proper response, But in the said format.
Please some one help me either parse this through angular methods, or get me a json type response from my spring controller.
TIA.
One of the solution is to transform the response object yourself using a function to handle the repsone when it returns...
This can be found at angular documentation.
$http({
url: '...',
method: 'GET',
//here you get the unparserd response ...
transformResponse: appendTransform($http.defaults.transformResponse,
//you data response comes here ..which you can handle customly
function(data) {
//perform modifications & get data
$scope.baselines = doTransform(data);
})
});
And then you can bind data to Html DOM as desired. This is for single get request.If you want to use it at all places , try to create a service or factory.
Thanks, HTH
The issue got solved. Actually in my pojo class for Baseline I had added following Json annotation.
private long id;
#JsonSerialize(as = BaselineRef.class)
#JsonRawValue
private BaselineRef bslRef;
private int size;
#JsonProperty
private boolean isDefault = false;
private boolean isOpen = true;
private boolean isDaily = false;
private String baselineDate;
private BaselineRef parentRef;
private Collection<String> activities;
Hence while retrieving I was getting following types of response.
[{"id":27885,"bslRef":acms.2016.04.00,"size":0,"isDefault":true,"baselineDate":null,"parentRef":null,"activities":null,"default":true,"open":true,"daily":false}].
Once i removed the annotation Now I am getting
`[{"id":27885,"bslRef":{"bslName":"2016.04.00","projectName":"acms","overrides":false},"size":0,"baselineDate":null,"parentRef":null,"activities":null,"default":true,"open":true,"daily":false}]`
which is my desired response. Here i ensured that BaselineRef has an toString method.
Here I dont have to parse in my angular code. Thanks for everyone help.
I have an angular js application, and when trying to issue the following post request :
$resource('api/'+API_VERSION+'/projects/:projectId/users/:userId')
.save(
{
projectId:$scope.project.id,
userId:id
},
{}
,function(){
// Handle callback
});
I get a 400 bad request error.
the request is handled by a spring RestController and the method looks like the following :
#RequestMapping(value = "/projects/{projectId}/users/{userID}",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
#RolesAllowed(AuthoritiesConstants.USER)
void addUsers(#PathVariable Long projectId, #PathVariable Long userId) {
log.debug("REST request to add admin to project");
projectService.addUser(projectId, userId);
}
I Checked the request that is been sent to the server, and nothing bad strikes me.
The url is correct (all parameter are of valid type), and the content type is set to Application json.
Thanks in advance for any help.
Your API consumes JSON and returns void, so I think you should have consumes = MediaType.APPLICAT_JSON_VALUE in your #RequestMapping.
[Edit]:
Apart from the consumes annotation everything is fine with your back-end. Can you try making your post request with the following code :
$resource('api/'+API_VERSION+'/projects/:projectId/users/:userId',
{projectId: $scope.project.id, userId: id}).$save();
or again, creating an instance of the resource :
var Project = $resource('api/'+API_VERSION+'/projects/:projectId/users/:userId',
{projectId: $scope.project.id, userId: id});
var newProject = new Project();
newProject.$save();
And let me know if it worked ?
Hi i am at my elementary stage in learning dropwizard with angularjs, my problem is that when i send response from my resource at server side as POJO, it gets parsed into JSON, but if i send any String, angular throws me error, please help me out how can i send my custom response to angular.
First step is to set the response type to plain text. This could be done like this:
#Path("/example")
#Produces(MediaType.TEXT_PLAIN)
public class EndPoint{
#GET
public Response saySomething() {
return Response.ok("plain text response").type(MediaType.TEXT_PLAIN).build();
}
}
once you have that covered you can use angular's $http service to read the plain text response:
$http({method: "GET", url: "/example"})
.success(function(data){
alert(data) // alert: plain text response
}
);