#RequestMapping(value = "/createItem", method = RequestMethod.POST)
#Override
public void createItem(#RequestParam(value="userId") String userId, #RequestParam(value="title") String title, #RequestParam(value="subtitle") String subtitle, #RequestParam(value="description") String description, #RequestParam(value="category") String category, #RequestParam(value="datapack") String datapack) {
this.itemDAO.createItem(userId, title, subtitle, description, category, datapack);
}
I am creating RESTful application with Spring. The method above works just fine, but when the datapack is longer than a certain length it will result in error. The error says...
Error parsing HTTP request header Note: further occurrences of HTTP
header parsing errors will be logged at DEBUG level.
I need to pass the datapack as a parameter and the datapack itself will be a json file which I convert it to string.
The datapack file might be very complex and big. How do I solve this?
Here's the example of the request:
http://localhost:8090/createItem?userId=test&title=test&subtitle=test&description=test&category=test&datapack=
{
"CLASS": "com.mincom.ellipse.edoi.ejb.menu_item.MENU_ITEMRec",
"INSTANCE": {
"m_creationDate": "20150824",
"m_creationTime": "001616",
"m_creationUser": "SR4187",
"m_lastModDate": "20150824",
"m_lastModTime": "001616",
"m_lastModUser": "SR4187",
"m_menuType": "",
"m_invokationString": "",
"primaryKey": {
"m_uuid": "3b4d95fe3dd3432fb00cde0cc25f903f"
}
}
},
{
"CLASS": "com.mincom.ellipse.edoi.ejb.i18n_descriptions.I18N_DESCRIPTIONSRec",
"INSTANCE": {
"m_creationDate": "20150824",
"m_creationTime": "001616",
"m_creationUser": "SR4187",
"m_lastModDate": "20150824",
"m_lastModTime": "001616",
"m_lastModUser": "SR4187",
"m_description": "CUSTOM_MENU",
"primaryKey": {
"m_locale": "en",
"m_uuid": "3b4d95fe3dd3432fb00cde0cc25f903f"
}
}
},
{
"CLASS": "com.mincom.ellipse.edoi.ejb.top_level_menus.TOP_LEVEL_MENUSRec",
"INSTANCE": {
"m_creationDate": "20150824",
"m_creationUser": "SR4187",
"m_lastModDate": "20150824",
"m_lastModTime": "001620",
"m_creationTime": "001620",
"m_lastModUser": "SR4187",
"m_uuid": "3b4d95fe3dd3432fb00cde0cc25f903f",
"primaryKey": {
"m_name": "SX"
}
}
}
Examples above works, but if I test with longer JSON file, it won't work.
Create a controller method that shall be receiving the JSON data posted by $http service using XHR (AJAX)
#RequestMapping(value = "/savecompany_json", method = RequestMethod.POST)
public #ResponseBody String saveCompany_JSON( #RequestBody Company company ) {
//
// Code processing the input parameters
//
return "JSON: The company name: " + company.getName() + ", Employees count: " + company.getEmployees() + ", Headoffice: " + company.getHeadoffice();
}
Create a POJO which maps to JSON object
public class Company {
private String name;
private long employees;
private String headoffice;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getEmployees() {
return employees;
}
public void setEmployees(Long employees) {
this.employees = employees;
}
public String getHeadoffice() {
return headoffice;
}
public void setHeadoffice(String headoffice) {
this.headoffice = headoffice;
}
}
Source
If the request is really big (like when sending files for instance), you might want to change your content-type in your http header. For instance (although might look differently depending on what you're actually sending):
$http({
method: 'POST',
url: url,
headers: {
'Content-Type': 'multipart/form-data'
},
data: {
data: model,
file: file
}
});
Then if the request is too big for the server to accept it, you might need to extend the request size limit. If you're using spring boot, you may go to your application.properties file (should be located under src/main/resources, but if it doesn't exist yet, create it manually) and add the following properties:
multipart.maxFileSize=3MB
multipart.maxRequestSize=3180KB
You are using a POST request anyhow, so simply send the parameters in the body with content type application/x-www-form-urlencoded like a normal form submission instead of in the URL.
Related
I'm trying to send and ajax post request to my springboot mvc controller, but with no success. I've looked a number of similar topics, tried the given solutions, but with no success at all.
If I change the request type to GET, it triggers the controller endpoint.
The endpoint function is not even being triggered in the controller. It is showing only the following error in browser console: jquery-3.4.1.js:9837 POST http://localhost:8080/rede-credenciada 500
I made the same request with postman and it gives the following error:
{
"timestamp": "2020-07-09T17:46:20.920+0000",
"status": 999,
"error": "None",
"message": "No message available"
}
Note: It only happens with POST request, if I change to GET, it works fine. The request is "listened" by the controller.
Here is my ajax request:
const json = {
idGrupoProcedimento: 0,
idTipoEspecialidade: $("#especialidade").val(),
uf: $("#estado").val(),
codCidade: $("#cidade").val()
}
const jsonString = JSON.stringify(json);
$.ajax({
url: "/rede-credenciada",
type: 'POST',
contentType: "application/json",
dataType: "application/json",
data: jsonString,
success: function(data){
console.log(data);
},
error: function(e) {
console.log(e.message);
}
});
Here, my endpoint:
#RequestMapping(value = "/rede-credenciada", method = RequestMethod.POST, consumes = "application/json")
#ResponseBody
public RedeCredenciadaResponse buscaRedeCredenciadaPorFiltro(#RequestBody RedeCredenciadaRequest request) {
... some logic
RedeCredenciadaResponse redeCredenciada = new RedeCredenciadaResponse();
redeCredenciada.setPessoasFisicas(pessoas);
redeCredenciada.setEmpresas(empresas);
return redeCredenciada;
}
And here is my wrapper class:
public class RedeCredenciadaRequest {
private int idGrupoProcedimento;
private int idTipoEspecialidade;
private String uf;
private String codCidade;
public int getIdGrupoProcedimento() {
return idGrupoProcedimento;
}
public void setIdGrupoProcedimento(int idGrupoProcedimento) {
this.idGrupoProcedimento = idGrupoProcedimento;
}
public int getIdTipoEspecialidade() {
return idTipoEspecialidade;
}
public void setIdTipoEspecialidade(int idTipoEspecialidade) {
this.idTipoEspecialidade = idTipoEspecialidade;
}
public String getUf() {
return uf;
}
public void setUf(String uf) {
this.uf = uf;
}
public String getCodCidade() {
return codCidade;
}
public void setCodCidade(String cidade) {
this.codCidade = cidade;
}
The error:
In your ajax request you are using dataType:'application/json', According to jQuery’s Ajax-Related Methods Description
// The type of data we expect back
dataType : "json",
Value of dataType shoud be json, or xml, or html, etc.
I have this class in my .NET application to send some data from client(.NET) to server(Spring) :
class NetworkController
{
private static readonly HttpClient client = new HttpClient();
public static async Task SendUserDataAsync()
{
var values = new Dictionary<string, string>
{
{ "firstName", "sunny" },
{ "lastName", "leone" },
{ "timeStamp", "test" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://localhost:8080/user", content);
var responseString = await response.Content.ReadAsStringAsync();
}
}
Reference
And in my Spring Boot application, I a class called User :
#Entity
public class User
{
#Id
private String firstName;
private String lastName;
private String timeStamp;
public User(){}
#Override
public String toString() {
return "firstName : "+this.firstName + "\n"+"lastName : " + this.lastName;
}
}
In my rest-controller I have this method to insert User :
#PostMapping("/user")
User addUser(#RequestBody User user)
{
System.out.println(user);//this always prints an empty line, maybe receiving nothing
return userRepository.save(user);
}
I get this warning Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported]
I have created this class(with the concept of Spring) in .NET, but it seems no use :
class User
{
String firstName;
String lastName;
String timeStamp;
public User()
{
firstName = "1"
lastName = "2"
timeStamp = "test"
}
}
Wouldn't sending an object instead of dictionary be more gentle and tidy ? How to do so ?
How can I resolve this problem ?
In your .NET application, the line var content = new FormUrlEncodedContent(values); indicates that the request will have a HTTP header Content-Type set to application/x-www-form-urlencoded.
It means the data stored in var values = new Dictionary... will be formatted by .NET as a query string such as firstName=sunny&lastName=leone&timeStamp=test.
That is what your Sprint server receives. However it wants to receive JSON data, not a query string. So it complains.
In order to get rid of the miscommunication, your .NET application should send JSON data, such as
{"firstName": "sunny", "lastName": "leone", "timeStamp": "test"},
as expected by the Spring server.
Here is an example code:
HttpClient client = new HttpClient();
object anonymousObject = new
{
firstName = "sunny",
lastName = "leone",
timeStamp = "test"
};
string jsonContent = JsonConvert.SerializeObject(anonymousObject);
var request = new HttpRequestMessage(HttpMethod.Post, "http://127.0.0.1:8080/user");
request.Content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.SendAsync(request);
Console.WriteLine(await response.Content.ReadAsStringAsync());
You need to install the package Newtonsoft.Json in order to call JsonConvert.SerializeObject(anonymousObject), as pointed by this SO answer mentionned by #alfcope.
We have an REST endpoint that will add a new empty ingredient to an existing meal:
#RequestMapping(value = "/add", method = RequestMethod.PUT, consumes = "application/json;charset=UTF-8")
public ResponseEntity<Object> add(#RequestBody final Meal meal) throws URISyntaxException
{
Optional<Meal> optionalMeal = mealRepository.findById(meal.getId());
if (!optionalMeal.isPresent()) {
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.body(MessageUtil.parse(MSG_404_MEAL, meal.getId() + ""));
}
Ingredient ingredient = new Ingredient();
ingredient.setMeal(optionalMeal.get());
ingredientRepository.saveAndFlush(ingredient);
ResponseEntity re = ResponseEntity
.created(RequestUtil.getResourceURI(ingredient.getId()))
.body(ingredient);
return re;
}
Ingredient is an entity class with some fields:
public class Ingredient implements Serializable
{
#Id
private Integer id;
private Meal meal;
private Grocery grocery;
private Float amount;
...
}
RequestUtil takes care of creating the URI where the newly created resource is to be found:
public class RequestUtil
{
public static URI getResourceURI(int id) throws URISyntaxException
{
final String url = RequestUtil.getCurrentRequest().getRequestURL().toString();
final String req = RequestUtil.omitLast(url);
return new URI(req + "get/" + id);
}
public static HttpServletRequest getCurrentRequest()
{
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
return ((ServletRequestAttributes) requestAttributes).getRequest();
}
public static String omitLast(final String url) {
return url.substring(0, url.lastIndexOf("/") + 1);
}
}
The http status code and resource URI end up correctly in the response headers, but the body contains two JSONs:
{
"id": 407,
"meal": {
"id": 99,
"name": "New Meal",
"active": true
},
"grocery": null,
"amount": null,
"bought": false
} {
"timestamp": "2018-08-29T19:25:31.466+0000",
"status": 201,
"error": "Created",
"message": "No message available",
"path": "/ingredient/add"
}
Our javascript code does not expect this extra data and fails with
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 114 of the JSON data
Using a debugger, we can see that by the time the code reaches the return statement in add(), the ResponseEntity does not contain this extra data. Can someone explain where it comes from, and how we stop it from polluting the response?
Thanks for any help!
I google this matter for hours but I still cannot find solution.
Here is my java code
#POST
public String doLogin(User user) {
System.out.println(" = " + user.getUsername());
return "";
}
and
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class User {
String username;
String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
and here is my AngularJs code
angular.module('notesApp', []).controller('MainCtrl', ['$http', function($http) {
var self = this;
self.submit = function() {
$http({
method: 'POST',
url: 'http://127.0.0.1:8080/Test/app/login',
headers : {'Content-Type': 'application/json'},
data: self.user //forms user object
})
.then(function(response) {
console.log(response.data);
return response.data;
}, function(response) {
});
}
}]);
My error message was:
SEVERE: A message body reader for Java class entity.User, and Java type class entity.User, and MIME media type application/json; charset=UTF-8 was not found, as I could not access 'user' Object in java code.
Could you please figure out which part I do wrong? Thank you so much.
You need to read from POST body and not Query Params.
You can use this:
#POST
public String doLogin( User user) {
System.out.println(" = " + user.getUsername());
return "";
}
#QueryParam is used to the queryparams which you'll pass as ?user=xyz#gmail.com
Remove query param You will get a serialized string. deSerialize it to User.
#POST
public String doLogin(User user) {
System.out.println(" = " + user.getUsername());
return "";
}
You are setting the data field on your POST. This sets the HTTP Body, not an HTTP query param.
Check the browser debugger networking panel to ensure that you are sending what you expect to the server. will open it and then 'send' your user and look at what is sent. Does this object look exactly like what User in java expects?
Hi everyone this is my first question here, hope you can help me with this issue I'm having right now.
I want to send a JSON Object using JQuery to a Spring Controller.
The format of the JSON Object is as follows:
{"ssoArray":["21212", "231341"], "groupArray":["g10002", "g10003"]}
But I got the error message: the request sent by the client was syntactically incorrect
My Environment:
Spring 3.0.6
jackson 1.9.13
JBoss 4.2
JQuery code:
Update: Added the full code of the javascript method that makes the ajax call
function addRemoveAdmin(action, ssoArray, groupArray) {
var uri = actionPath + "/";
var jsonParameter = {"ssoArray":ssoArray, "groupArray":groupArray};
if(action == "add") {
uri = uri + addAdminAction;
} else {
uri = uri + removeAdminAction;
}
console.log(typeof jsonParameter);
$.ajax({
url:uri,
type:"POST",
data:jsonParameter,
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(){
alert(data);
}
});
}
Controller code:
#RequestMapping(value = "/addAdmin", method = RequestMethod.POST)
public String addAdmin(#RequestBody final AdminAndGroup personsAndGroups) throws Exception {
LOGGER.info("[RequestController] - addAdmin start");
LOGGER.info(personsAndGroups.toString());
return "OK";
}
Mapping class:
public class AdminAndGroup implements Serializable {
private static final long serialVersionUID = 9024455757311860269L;
private List<String> ssoArray;
private List<String> groupArray;
public AdminAndGroup(){}
public List<String> getSsoArray() {
return ssoArray;
}
public void setSsoArray(List<String> ssoArray) {
this.ssoArray = ssoArray;
}
public List<String> getGroupArray() {
return groupArray;
}
public void setGroupArray(List<String> groupArray) {
this.groupArray = groupArray;
}
#Override
public String toString() {
return "AdminAndGroup [ssoArray=" + ssoArray + ", groupArray="
+ groupArray + "]";
}
}
I have used java.util.List to map the arrays that come inside the JSON Object but I'm not sure if this is the right way to tackle the issue.
Also I have searched in Stack Overflow and I haven't found an example on how to map arrays inside a JSON Object.
Thanks in advance.
If you want to send json, you must convert your object to json. Otherwise, jQuery will convert it to a param string
data: JSON.stringify(jsonParameter)