I keep receiving null values while sending these two parameters thru a POST with ajax (tried with Poster as well):
#POST
#Path("/update")
#Produces(MediaType.APPLICATION_JSON)
public void update(String Path, String Content) {
updateURI(Path,Content);
}
Path: http://essam.ldm.io/stor...amblog/ChannelList/ch1/post2
Content: <http://essam.ldm.io/storage/essamblog/ChannelList/ch1/post2> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://crosscloud/mblog/Post>. <http://essam.ldm.io/storage/essamblog/ChannelList/ch1/post2> <http://crosscloud/mblog/owner> <https://essam.ldm.io></https:>. <http://essam.ldm.io/storage/essamblog/ChannelList/ch1/post2> <http://purl.org/dc/terms/created> <2013-03-06T16:41:18+0300^^http://www.w3.org/2001/XMLSchema#dateTime>. <http://essam.ldm.io/storage/essamblog/ChannelList/ch1/post2> <http://rdfs.org/sioc/ns#content>.
Obviously I cannot send them as #QueryParam or #PathParam due to the format.
It is irrilevant putting the jQuery code since it deosnt wotk with Poster neither, but here it is:
function doUpdate(path, rdf)
{
var obj1 = {"path": path, "rdf": rdf};
var sUrl = "http://localhost:8080/browsing/services/RDF/update";
$.ajax({
type: "POST",
url: sUrl,
contentType: "application/json; charset=utf-8",
data: obj1,
//dataType: "json",
async: false,
success: function (resp, status, xhr) {
$("#message").html("STATUS: " + xhr.status + " " + xhr.statusText + "\n" + resp);
$("#message").hide();
$("#login_message").html("<font color='green'><b>Record succesfully updated</b></font>d");
},
error: function(resp, status, xhr){
$("#message").html("ERROR: " + resp.status + " " + resp.statusText + "\n" + xhr);
$("#message").show();
}
});
}
Anything I am doing wrong?
Thanks,
You can encode it (i.e. base64) before you send it and decode it on server or you can use JSON as request param.
Using JSON, for example;
#POST
#Path("/update")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public void update(PathContext ctx) {
updateURI(ctx.getPath(),ctx.getContent());
}
#XmlRootElement
public class PathContext {
private String path;
private String content;
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
Your JSON will look like;
{"path": somePath, "content": someContent}
Hope it helps.
Related
ERROR:
The resource identified by this request is only capable of generating
responses with characteristics not acceptable according to the request
"accept" headers.
Here is my Ajax code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
/* function new_element(){ */
$(document).ready(function(){
$("#search").click(function(){
console.log("fetched list");
$.ajax({
url: "http://localhost:8080/SpringMvcJdbcTemplate/listContact",
type : "GET",
dataType : 'json',
/* contentType : "application/json", */
accept : "application/json",
success : function(data) {
alert(this.getResponseHeader("Content-Type"));
console.log("SUCCESS: ", data);
display(data);
},
error : function(e) {
console.log("ERROR: ", e);
display(e);
}
});
});
});
function display(data) {
console.log("inside func list");
var json = "<h4>Ajax Response</h4><pre>"
+ JSON.stringify(data, null, 4) + "</pre>";
$('#feedback').html(json);
}
</script>
The controller class
#JsonView(Views.Public.class)
#RequestMapping(value = "/listContact",
method = RequestMethod.GET,
produces=MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public AjaxResponseBody listContact(ModelAndView model) throws IOException {
List<Contact> listContact = contactDAO.list();
System.out.println("listContact");
List<Contactdup> listContdup = new ArrayList<Contactdup>();
Contactdup contactdup = null ;
AjaxResponseBody result = new AjaxResponseBody();
for(Contact contact:listContact) {
contactdup = new Contactdup();
contactdup.setFname(contact.getFname());
System.out.println("inside for");
System.out.println(contact.getFname());
listContdup.add(contactdup);
}
result.setResult(listContdup);
result.setCode("200");
result.setMsg("");
return result;
}
AjaxResponseBody:
package ajaxrespose;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonView;
import net.codejava.spring.model.Contactdup;
import net.codejava.spring.model.Views;
public class AjaxResponseBody {
public List<Contactdup> getResult() {
return result;
}
public void setResult(List<Contactdup> result) {
this.result = result;
}
#JsonView(Views.Public.class)
String msg;
#JsonView(Views.Public.class)
String code;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
#JsonView(Views.Public.class)
List<Contactdup> result;
}
The route you are calling is probably not returning content-type "application/json".
I made a post request method with Retrofit2 but I encountered this problem on my response.
Expected a string but was BEGIN_OBJECT at line 3 column 4 path $.SUCCESS
The response should be
{
"SUCCESS" :
{
"200" : "access granted",
"ra" : "approved",
"la" : "approved",
"ch" : "approved"
}
}
I uses this code for the post request
#POST("login")
Call<Post> createPost(#Body Post post);
And for the POJO class
public class Post {
private String anthony;
private String SUCCESS;
public Post(String name) {
this.anthony = name;
}
public String getSUCCESS() {
return SUCCESS;
}
}
For the method I use the following code
private void createPost() {
Post post = new Post("mypassword");
Call<Post> call = jsonPlaceHolderApi.createPost(post);
call.enqueue(new Callback<Post>() {
#Override
public void onResponse(Call<Post> call, Response<Post> response) {
if (!response.isSuccessful()) {
textViewResult.setText("Code: " + response.code());
return;
}
Post postResponse = response.body();
String content = "";
content += "Code: " + response.code() + "\n";
content += "S" + postResponse.getSUCCESS();
textViewResult.setText(content);
}
#Override
public void onFailure(Call<Post> call, Throwable t) {
textViewResult.setText(t.getMessage());
}
});
}
Does anyone know what's wrong with my code? I expected to get the response inside the "SUCCESS" json object.
You expect SUCCESS to be an object in your wanted response but you have defined it as a String in your Post class. You should use an object for SUCCESS instead.
public class Post {
private String anthony;
private PostSuccess SUCCESS;
public Post(String name) {
this.anthony = name;
}
public PostSuccess getSUCCESS() {
return SUCCESS;
}
}
public class PostSuccess {
#JsonProperty("200")
private String _200;
private String ra;
private String la;
private String ch;
}
This is my jsp page home.jp
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#sampleForm').click(
function(event) {
var firstname = "Chethan";
var age = 12;
var json = {
"name":firstname,
"age":age
}
alert(json)
$.ajax({
url : "/com/testAjacCall",
data: JSON.stringify(json),
type : "POST",
mimeType: 'application/json',
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success : function(response) {
alert("SUCCESS--->"+ response );
},
error : function(error) {
alert("error---->"+error);
}
});
return false;
});
});
</script>
This is my controller HomeController.java
#RequestMapping(value = "/testAjacCall", method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody String processAJAXRequest(#RequestBody Person person ,HttpServletResponse response) {
String jQresponse = "Hello";
System.out.println("IAMWORKING");
// Process the request
// Prepare the response string
return jQresponse;
}
and this is my POJO Person.java
public class Person {
String name;
int age;
public Person(){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Getting
HTTP Status 415 -message-description-The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
I tried many solutions but i am not able to find my mistake. please do help me where i am going wrong.
I have written some sort of code to send data from client to spring model. and want that json data should automatically fill the java class. but not able to do this.
Jquery looks like this
$('#login-form').submit(function(event){
var username = $('#id_username').val();
var password = $('#id_password').val();
alert(username + password)
var json = { "loginId" : username, "password" : password};
$.ajax({
type: "POST",
url: $("#login-form").attr("action"),
data: JSON.stringify(json),
beforeSend: function(xhr){
var mess = validateForm();
if(mess.length != 0){
$('#error-mes').show();
$('#error-mes').html(mess);
event.preventDefault();
return false;
}
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
return true;
},
success: function(response){
$('#error-mes').html(response);
$('#error-mes').show();
},
error: function(e){
alert('Error: ' + e);
}
});
event.preventDefault();
$('#userName').hide();
$('#spn_password').hide();
});
Spring code like this
#RequestMapping(value = "/signin", method = RequestMethod.POST )
public #ResponseBody String submitCustSignInForm(HttpServletRequest request, #ModelAttribute("model") Person model,
HttpSession sess) {
String response = "";
Person person = null;
if (sess.getAttribute("USER_INFO") == null) {
person = tsService.login(model);
if (person == null) {
response = "User name or password does not match.";
} else {
response = "success";
sess.setAttribute("USER_INFO", person);
}
}
return response;
}
Person model has same loginId and password attribute and setter and getter in class.
can some body tell me how can it achieved.
I have implemented a RESTful web Service in java which inserts data into MySQL db, I have tested this using POSTER in mozila firefox and also in google chrome. My Web Service takes a String with the POST request, now I am unable to utilize WEB SERVICE using JS: the code making POST request on WEB SERVICE URL is as follows:
$.ajax({
url: 'http://localhost:8080/AgentWS/webresources/Items',
type: 'POST',
contentType: 'application/xml',
dataType: 'xml',
data: 'content='+content,
success: function (data) {
alert(content);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + errorThrown);
}
});
The alert in success function is also not displayed plus the dialog error is showing a dialog with : Error: on it'
Server Side code is:
#POST
#Consumes("application/xml")
#Produces("application/xml")
public String postXml(String content) {
//TODO
// return Response.created(context.getAbsolutePath()).build();
StringTokenizer sp = new StringTokenizer(content, "&");
String agentName = sp.nextToken();
String agentId = sp.nextToken();
String agentState = sp.nextToken();
String agentExtension = sp.nextToken();
String agentDeviceState = sp.nextToken();
String agentDeviceStateChangeTime = sp.nextToken();
DBConection conn = new DBConection();
conn.insertAgentActivityInfo(agentName, agentId, agentState, agentExtension, agentDeviceState, agentDeviceStateChangeTime);
return agentName + " " + agentId + " " + agentState + " " + agentExtension + " " + agentDeviceState + " " + agentDeviceStateChangeTime;
}
I think the problem is with the data you are sending,
data: 'content='+content should be replaced with a name for the parameter like
data: {content:'content='+content}
and check what you are doing on the server side
My guess is that data: 'content='+content, is posting invalid XML to the server and you are getting 500 Internal Server Error. Can you try setting the data to just the XML content? like
...
data: content,
....
EDIT
If all you want is a simple post
Java
#POST
public String postXml(String content) {
//TODO
// return Response.created(context.getAbsolutePath()).build();
StringTokenizer sp = new StringTokenizer(content, "&");
String agentName = sp.nextToken();
...
return agentName + " " + agentId + " " + agentState + " " + agentExtension + " " + agentDeviceState + " " + agentDeviceStateChangeTime;
}
Javascript
$.ajax({
url: '/AgentWS/webresources/Items',
type: 'POST',
data: 'content=1&2&3&4&5&5',
success: function (data) {
alert(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + errorThrown);
}
});
Here's what i think, you should write a model class Agent in server side like this :
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Agent
{
private String agentName;
private String agentId;
private String agentState;
private String agentExtension;
private String agentDeviceState;
private String agentDeviceStateChangeTime;
public String getAgentName() {
return agentName;
}
public void setAgentName(String agentName) {
this.agentName = agentName;
}
public String getAgentId() {
return agentId;
}
public void setAgentId(String agentId) {
this.agentId = agentId;
}
public String getAgentState() {
return agentState;
}
public void setAgentState(String agentState) {
this.agentState = agentState;
}
public String getAgentExtension() {
return agentExtension;
}
public void setAgentExtension(String agentExtension) {
this.agentExtension = agentExtension;
}
public String getAgentDeviceState() {
return agentDeviceState;
}
public void setAgentDeviceState(String agentDeviceState) {
this.agentDeviceState = agentDeviceState;
}
public String getAgentDeviceStateChangeTime() {
return agentDeviceStateChangeTime;
}
public void setAgentDeviceStateChangeTime(String agentDeviceStateChangeTime) {
this.agentDeviceStateChangeTime = agentDeviceStateChangeTime;
}
}
And the server rest service that you have should be changed little bit :
#POST
#Consumes("application/xml")
#Produces("application/xml")
public String postXml(Agent agent) {}
Inside this method you can use "agent" object, that is passed, to retrieve all the values sent by the client like agent.getAgentName()
Now the payload(or request body) that should contain something like this:
<Agent>
<agentName></agentName>
<agentId></agentId>
<agentState></agentState>
<agentExtension></agentExtension>
<agentDeviceState></agentDeviceState>
<agentDeviceStateChangeTime></agentDeviceStateChangeTime>
</Agent>
I hope it is of some assistance.
Hard to guess without the error code and message but:
change
data: 'content='+content
to
data: { content : content } // format as json
And in your java resource:
#POST
#Consumes(MediaType.APPLICATION_JSON)
public String postXml(String content)
// read content as json