Returing a JSONObject right now from a restful webservice using Jersey. Its working perfectly fine and returning a JSSONObject as follows.
#GET
#Path("/LoginGetValues")
#Produces({"application/x-javascript"})
public JSONObject GetValues(#QueryParam("request") String request)
{ ...
JSONObject value = new JSONObject();
value = null ;
return value ;
}
But intending to convert that response into JsonP response , tried to append that with a callback function (as the following refering ( here) but then not getting the required response , indeed its asking to define the #JSONP annotation . Also if i have to define the callback then how and where i have to do that ! Kindly help to get a JSONP response
#GET
#JSONP(queryParam="callback")
#Path("/LoginGetValues")
#Produces({"application/x-javascript"})
public JSONWithPadding GetValues( #QueryParam("callback") String callback ,#QueryParam("request") String request)
{ ...
JSONObject value = new JSONObject();
value = null ;
return new JSONWithPadding(value , callback);
}
Related
Following is my controller
#RestController
#RequestMapping("identity/v1/")
public class InvestigateTargetController {
#RequestMapping(method = RequestMethod.POST, value = "receive",
produces = OneplatformMediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<InvestigateOutputResource>
processRequest(#RequestBody JSONObject jsonObject) {
System.out.println(jsonObject.toString());
return new ResponseEntity<>(HttpStatus.OK);
}
}
I am trying to send a json object to this controller via POSTMAN. But when I print jsonObject.toString() the output is {} ( empty ). Following are snapshots of POSTMAN:
Where am I going wrong ?
Create a java class having properties (with getters and setters) same as json object and put it as requestbody.
Solved it. Instead of JSONObject catch it in a string type.
I am trying to send following Integer value to server.
int mStoreArea;
I use this link as REST client.
here is Request:
RestClient client = new RestClient(my_url);
client.AddParam("area", String.valueOf(c.getStoreArea()));
and the Error I face is : Int value required!
I retrieve this integer from a json object saved to a file, its procedure is described below:
public myClass(JSONObject json) throws JSONException {
mStoreArea = json.optInt(JSON_TAG);
}
public JSONObject toJSON() throws JSONException {
JSONObject json = new JSONObject();
json.put(JSON_TAG, mStoreArea);
return json;
}
I think you should use this:
client.AddParam("area", Integer.parseInt(c.getStoreArea()));
I have created 2 web services and I was able to send some data.
Using this three lines of code
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("http://localhost/<appln-folder-name>/method/domethod?data1=abc&data2=xyz");
HttpResponse response = client.execute(request);
In this situation, the method that I posted send to a Web Server the 2 data.
#Path("/domethod")
// Produces JSON as response
#Produces(MediaType.APPLICATION_JSON)
// Query parameters are parameters: http://localhost/<appln-folder-name>/method/domethod?data1=abc&data2=xyz
public String doLogin(#QueryParam("data1") String d1, #QueryParam("data2") String d2){
String response = "";
System.out.println("Data: d1="+d1+"; d2="+d2);
if(checkData(d1, d1)){
response = Utitlity.constructJSON("tag",true);
}else{
response = Utitlity.constructJSON("tag", false, "Error");
}
return response;
}
System.out works correctely and print: d1=abc; d2=xyz
But now the application isn't able to return response to the first method.
How I can get the response?
You're already getting the response here:
HttpResponse response = client.execute(request);
And since you're already using org.apache.httpcomponents you can do something like:
String result = EntityUtils.toString(response.getEntity());
After that you have your data as a string, simply do what you wish with it.
EDIT:
A little bit more information, your data is in the entity of the response, which is an HttpEntity object. You can get the content from there as an InputStream and read it as you wish, my example was for a simple string.
First of all, I would annotate with get the method. Then I would use a Java Class and let the library convert the class to json for me.
Try to do this:
#GET
#Path("/domethod")
// Produces JSON as response
#Produces(MediaType.APPLICATION_JSON)
// Query parameters are parameters: http://localhost/<appln-folder-name>/method/domethod?data1=abc&data2=xyz
public String doLogin(#QueryParam("data1") String d1, #QueryParam("data2") String d2){
Response response = new Response();
System.out.println("Data: d1="+d1+"; d2="+d2);
if(checkData(d1, d1)){
//set in response the tag property to true and maybe another property to OK
response.setTag(true);
response.setStatus("OK");
}else{
//set in response the tag property to false and maybe another property to ERROR
response.setTag(false);
response.setStatus("ERROR");
}
return response;
}
I'm having trouble sending a json object from javascript to java controller,
Ajax:
var xmlHttp = getXmlHttpRequestObject();
if(xmlHttp) {
var jsonObj = JSON.stringify({"title": "Hello","id": 5 });
xmlHttp.open("POST","myController",true);
xmlHttp.onreadystatechange = handleServletPost;
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.send(jsonObj);
}
function handleServletPost() {
if (xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
alert(window.succes);
}
}
}
What I tried in Java:
public void process(
final HttpServletRequest request, final HttpServletResponse response,
final ServletContext servletContext, final TemplateEngine templateEngine)
throws Exception {
String jsonObj = request.getParameter("jsonObj");
}
They all are null.
I tried reading related posts and multiple ways of sending the data but same result. I don't know how to use Jquery for ajax, so I'm looking for a js solution mainly.
Can someone tell me what I'm missing? As I spent about three hours trying to figure it out
To get your JSON sent with a POST request, you have to read the body of the request in a doPost method. Here's one way to do it :
protected void doPost(HttpServletRequest hreq, HttpServletResponse hres)
throws ServletException, IOException {
StringWriter sw = new StringWriter();
IOUtils.copy(hreq.getInputStream(), sw, "UTF-8");
String json = sw.toString();
And then you'll have to parse the JSON. This may be done for example using Google gson.
Supposing you have a class Thing with public parameters id and title, this would be
Gson gson = new GsonBuilder().create();
Thing thing = gson.fromJson(json, Thing.class);
int id = thing.id;
String title = thing.title;
Of course there are other solutions than gson to parse JSON but you have to parse it.
I think you are confusing URL parameters with request body. To get json string from request you need read it from request.getReader().
I have figured it out.
The Json should be sent like this:
xmlHttp.send("jsonObj="+jsonObj);
instead of
xmlHttp.send(jsonObj);
In order to receive it as parameter.
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();
}