Well I have gone through most of the questions regarding this topic in SO but not able to fix this issue.
My question is whenever I am using #RequestBody annotation within the below controller method, the ajax call never invokes this method but if I remove the #RequestBody annotation, the control comes in the method but having null values for contact object: Why the serialized form is not getting bind to the object?
and getting error: The request sent by the client was syntactically incorrect
controller:
#RequestMapping(value="/addContacts.htm", method = RequestMethod.POST, headers = {"content-type=application/json"})
#ResponseBody
public String addContacts(#RequestBody Contact contact, HttpServletRequest request ) {
return "success";
}
ajax call:
$("#add_more_contact").click(function(){
var formJson = $("#addContactForm").serialize();
$.ajax( {
url : "/myproject/admin/addContacts.htm",
type : "POST",
data : formJson,
dataType : "text",
contentType : "application/json",
success : function(data) {
alert('Success - '+data);
},
error : function(xhr, desc, err) {
alert("Desc: " + desc + "\nErr:" + err);
}
});
});
POST data in ajax request: these 4 variables are present in my Contact object.
firstName=bill&lastName=gates&email=&mobileNumber=
project-servlet.xml:
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes" value="application/json"/>
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jacksonMessageConverter" />
</list>
</property>
</bean>
<mvc:annotation-driven/>
Using jackson jar : jackson-all-1.9.9.jar
Not sure what I am missing??Any help will be highly appreciated.
The HTTP 400 Bad Request (The request sent by the client was syntactically incorrect) error occurs when the client did not send a syntactically correct entity.
In this case, the request body is expected to be a valid json, but it wasn't. As #Dave mentioned, your request does not contain a JSON, but a urlencoded string such as name=stack&value=overflow. Instead, it should be a JSON, such as {"name":"stack", "value":"overflow"}.
To achieve this, please refer to another good thread : Convert form data to JavaScript object with jQuery .
A possible fix of your code:
$("#add_more_contact").click(function(){
var formJson = $("#addContactForm").serializeToObject(); // use plugin, or build by yourself
// this variable should be a javascript object,
// such as {"name":"stack", "value":"overflow"}
$.ajax( {
url : "/myproject/admin/addContacts.htm",
type : "POST",
data : JSON.stringify(formJson), // serialize javascript object to JSON 'string'
dataType : "json", // 'text' -> 'json'
contentType : "application/json", // this can be omitted
success : ...,
error : ...,
});
});
You're serializing as form data not json ... Build an anonymous map of your form data and pass that
Related
I'm currently trying to make an API doc page thanks to nelmio-api-bundle. I only have one route which is a POST route. I'm receiving a JSON in the body of the request and I'm using the Serializer from symfony to deserialize it in a DTO. I'm also using a DTO for the response (which contains the status code, a bool set to true or false, and a message). Now I'm trying to use these DTO (for input and output) to build the API documentation with nelmio-api-bundle but how to make it ? I'm using PHP8.1 attributes to make it, for response it almost works (except that the response is shows as an array) but I don't know how to make it for the inputs.
Here is my current code:
#[Route('/user', methods: ['POST'])]
#[OA\Parameter(
name: 'user',
description: 'The user information in JSON',
in: 'query',
required: true
)]
#[OA\Response(
response: 200,
description: 'Returns the success response',
content: new OA\JsonContent(
type: 'array',
items: new OA\Items(ref: new Model(type: SuccessResponseDTO::class))
)
)]
public function registerUser(Request $request, LoggerInterface $logger): JsonResponse
{
//the code to register the user
}
And here is the result:
Do someone know how to make it ?
I have an issue with AFNetworking and AFJSONRequestSerializer. I try to access an API, and the request contains a text/plain header. Here's my code :
class BaseService {
var manager: AFHTTPRequestOperationManager!
init() {
manager = AFHTTPRequestOperationManager()
manager.responseSerializer = AFJSONResponseSerializer()
manager.requestSerializer = AFJSONRequestSerializer(writingOptions: NSJSONWritingOptions.allZeros)
}
}
class UserService: BaseService {
func startNewEntry(name: String) {
let params = [
"time_entry": [
"description": name,
"created_with": "fooBar"
]
]
manager.POST(
"endpoint",
parameters: params,
success: { (operation, response) -> Void in
let json = JSON(response)
println("OK")
println(json)
Context.shared.entries.getFromJSON(json)
}) { (operation, error) -> Void in
println("-- ERROR --")
println(operation)
println(error)
}
}
Do you know this issue ?
No, this code will create a request with a content type of application/json. But I wonder if you perhaps mislead by an error message that said:
Request failed: unacceptable content-type: text/html
If you got that, that's not telling you that that the request had an unacceptable content type, but rather that the request failed because the response was text/html. And this is a very common issue: If server code that is attempting to create a JSON response fails for some reason, sometimes the error message isn't JSON, but rather it's HTML.
I would suggest adding the following inside the failure block of your POST method in order to see what this text/html response was:
if operation.responseData != nil {
println(NSString(data: operation.responseData, encoding: NSUTF8StringEncoding))
}
This way, if you get a text error message from the server (e.g. the request was malformed or what have you), you'll be able to read the HTML response you got back.
I am getting a problem in worklight adapter , In the following http adapter method
,it is showing The mandatory parameter 'action' is missing, returning statusCode as
500 and statusReason as "Internal Server Error". I had given all the user credentials
correctly in adapter xml file, but I don't know why I'm getting this error.
Code:
function actionOnProcessInstance()
{
var param = "/rest/bpm/bfm/v1/process/_PI:9003013d.4387342e.1efe573f.7c20307?action=resume";
var input =
{
method : 'put',
returnedContentType : 'json',
path : param,
};
var response = WL.Server.invokeHttp(input);
return response;
}
In 5.0.5.x, invokeHttp will take any params provided on the path for put and post and place them inside the http body instead of having them remain on the path as query params (as the developer probably intended). This behavior will be updated in an upcoming version but for now there's no way to force these to stay as query params.
I'm trying to call a REST webservice using dojo toolkit it seems that the call is encountring some isues this is the call with dojo
dojo.xhrGet({
url: 'http://localhost:9080/TestJMSWeb/jaxrs/categories/all',
handleAs: 'json',
timeout: 2000,
load: callback
});
var callback = dojo.hitch(this, function(data) {
var massagedData = {
label: 'categorie',
identifier: 'id',
items: data
}
this.store = new dojo.data.ItemFileReadStore({data: massagedData});
});
the webservice code is here
#GET
#Path("/all")
#Produces("application/json")
public JSONArray getAllCategories() throws IOException {
final List<Categorie> allCategories = manager.getCategories();
if (allCategories == null || allCategories.isEmpty())
throw new WebApplicationException(ErrorUtil.jSONArrayResponse(Status.NO_CONTENT, "No category found"));
JSONArray jsonArray = jsonCustomerArray(allCategories);
return jsonArray;
}
when I call the webservice I get an error message
ResourceRegis I org.apache.wink.server.internal.registry.ResourceRegistry filterDispatchMethods The system cannot find any method in the ressources.CategorieRessouce class that supports OPTIONS. Verify that a method exists.
[4/24/12 1:23:41:531 GMT] 0000002f SystemErr R 0 TestJMSWeb INFO [WebContainer : 0] openjpa.Runtime - OpenJPA dynamically loaded a validation provider.
it seems that is trying to call the ressource with the OPTIONS method while I'm using the .xhrGet function what is the problem?
Here is a link describing the problem: http://engin.bzzzt.biz/2010/01/22/first-dojo-impression/
The guy talks about how if it is a cross domain request (which I believe yours is, because of the ports), and the request contains some Access-Control-* HTTP headers, than browsers will send the request as OPTIONS instead of GET.
Dojo adds the Access-Control-* headers when it determines you are making a cross domain request. You can try to fix this yourself by going to dojo/_base/xhr.js and commenting out the following lines (723 to 729):
// FIXME: is this appropriate for all content types?
if(args.contentType !== false){
xhr.setRequestHeader("Content-Type", args.contentType || _defaultContentType);
}
if(!args.headers || !("X-Requested-With" in args.headers)){
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
I haven't tried this fix yet so please let me know if it works!
I am struggling to differentiate the response MIME type in sencha touch. My login service is designed in such a way that if the login success then it will give me a JSON object. If it failed to authenticate, then it will return a plan error text.
How can i find the difference? My request looks like this.
Ext.Ajax.request({
url : 'http://xxxx.com/Sencha/LoginServlet?userid='+ agentid + "&password=" + password,
type:'json',
success : function(response, opt) {
alert("response text" + response.responseText);
var obj = Ext.decode(response.responseText);
console.dir(obj);
App.views.viewport.reveal('nextScreen');
},
failure : function(response, opt) {
Ext.Msg.alert('Failed', response.responseText);
}
});
Ext JS internally uses the XMLHttpRequest Object, so the reponse is w3 consortium compliant. Hence you can retrieve the response object properties like in normal javascript. Example :
response.getResponseHeader("Content-Type")
For details on how to retrieve other details from the response object see here.