Restlet implementing post with json receive and response - json

First, what i wanted to know is what i am doing is the right way to do it.
I have a scenario where i have will receive a json request and i have to update the database with that, once the db is updated i have to respond back with the json acknowledgment.
What i have done so far is create the class extending application as follows:
#Override
public Restlet createRoot() {
// Create a router Restlet that routes each call to a
// new instance of ScanRequestResource.
Router router = new Router(getContext());
// Defines only one route
router.attach("/request", RequestResource.class);
return router;
}
My resource class is extending the ServerResource and i have the following method in my resource class
#Post("json")
public Representation post() throws ResourceException {
try {
Representation entity = getRequestEntity();
JsonRepresentation represent = new JsonRepresentation(entity);
JSONObject jsonobject = represent.toJsonObject();
JSONObject json = jsonobject.getJSONObject("request");
getResponse().setStatus(Status.SUCCESS_ACCEPTED);
StringBuffer sb = new StringBuffer();
ScanRequestAck ack = new ScanRequestAck();
ack.statusURL = "http://localhost:8080/status/2713";
Representation rep = new JsonRepresentation(ack.asJSON());
return rep;
} catch (Exception e) {
getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
}
My first concern is the object i receive in the entity is inputrepresentation so when i fetch the jsonobject from the jsonrepresentation created i always get empty/null object.
I have tried passing the json request with the following code as well as the client attached
function submitjson(){
alert("Alert 1");
$.ajax({
type: "POST",
url: "http://localhost:8080/thoughtclicksWeb/request",
contentType: "application/json; charset=utf-8",
data: "{request{id:1, request-url:http://thoughtclicks.com/status}}",
dataType: "json",
success: function(msg){
//alert("testing alert");
alert(msg);
}
});
};
Client used to call
ClientResource requestResource = new ClientResource("http://localhost:8080/thoughtclicksWeb/request");
Representation rep = new JsonRepresentation(new JSONObject(jsonstring));
rep.setMediaType(MediaType.APPLICATION_JSON);
Representation reply = requestResource.post(rep);
Any help or clues on this is hight appreciated ?
Thanks,
Rahul

Using just 1 JAR jse-x.y.z/lib/org.restlet.jar, you could construct JSON by hand at the client side for simple requests:
ClientResource res = new ClientResource("http://localhost:9191/something/other");
StringRepresentation s = new StringRepresentation("" +
"{\n" +
"\t\"name\" : \"bank1\"\n" +
"}");
res.post(s).write(System.out);
At the server side, using just 2 JARs - gson-x.y.z.jar and jse-x.y.z/lib/org.restlet.jar:
public class BankResource extends ServerResource {
#Get("json")
public String listBanks() {
JsonArray banksArray = new JsonArray();
for (String s : names) {
banksArray.add(new JsonPrimitive(s));
}
JsonObject j = new JsonObject();
j.add("banks", banksArray);
return j.toString();
}
#Post
public Representation createBank(Representation r) throws IOException {
String s = r.getText();
JsonObject j = new JsonParser().parse(s).getAsJsonObject();
JsonElement name = j.get("name");
.. (more) .. ..
//Send list on creation.
return new StringRepresentation(listBanks(), MediaType.TEXT_PLAIN);
}
}

When I use the following JSON as the request, it works:
{"request": {"id": "1", "request-url": "http://thoughtclicks.com/status"}}
Notice the double quotes and additional colon that aren't in your sample.

Related

Returning result as JSON instead of HTML

I am calling and displaying a java web service using ASP.NET Web API. How do i make it such that when i run my ASP.NET Web API, the page shows JSON data instead of HTML?
Here are my codes:
DemoRestfulClient.cs
public class DemoRestfulClient
{
private string BASE_URL = "http://localhost:8080/";
public Task<string> AdditionJava2()
{
{
try
{
var client = new HttpClient();
client.BaseAddress = new Uri(BASE_URL);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("AdditionJava2").Result;
return response.Content.ReadAsStringAsync();
}
catch (Exception e)
{
HttpContext.Current.Server.Transfer("ErrorPage.html");
}
return null;
}
}
}
DemoController.cs
public class DemoController : Controller
{
private DemoRestfulClient demoRestfulClient = new DemoRestfulClient();
public ActionResult Index()
{
var Result1 = demoRestfulClient.AdditionJava2().Result;
return Content(Result1);
}
}
Someone please help me. Thank you so much in advance.
public class DemoController : Controller
{
private DemoRestfulClient demoRestfulClient = new DemoRestfulClient();
public ActionResult Index()
{
var Result1 = demoRestfulClient.AdditionJava2().Result;
return Json(Result1);
}
}
The above method will return a json object .
You have wanted to get the json object, right? :)
You have to parse the Json object in order to separately view the content in json.
By using ajax, you can get the content of the json object separately.
For an example,
$.ajax({
url: $("#head").val() + "/Template/updatedTmpltView",
dataType: "html",
data: {},
type: "POST",
success: function (msg) {
data = $.parseJSON(msg)
var name = data.FieldName;
var type = data.FieldType;
var id = data.FieldId;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
In the success (msg), you get the json object as **msg**.
data will include the parsed json object and you can obtain necessary data by data.yourFieldName
Hope this helped you! :)

Send Json Object to Spring Controller

Hy guys.
I have this js code, where I create an object to send to a Spring controller via Ajax function:
$('#eventsdatageneral').on('click', '.btn.btn-info', function(event)
{
var today_date = new Date().getTime();
var dataToSend = new Object();
dataToSend.dateToSend = today_date;
dataToSend.nameToSend = host_name;
dataToSend.typeToSend = type_name;
console.log(dataToSend);
event.preventDefault();
//here starts the code to sending data to Spring controller
$.ajax({
url: "../todaydatarecover.json",
type: "post",
data: dataToSend,
success : function() {
console.log("Invio riuscito.");
//console.log(moment(today_date).format('DD/MM/YYYY'));
}
});
});
This is the controller:
#PostMapping(value="/todaydatarecover.json")
#ResponseBody
public ModelAndView todayInfoAndIdRecover(ModelAndView model, HttpServletRequest request,
#RequestParam(name="dateToSend", required=false) long dateInBox,
#RequestParam(name="nameToSend", required=false) String nameInBox,
#RequestParam(name="typeToSend", required=false) String typeInBox) throws IOException
{
//First of all, we invoke getinfo methods to take info and id
Timestamp date = new Timestamp(dateInBox);
Events event = networks.getInfoandId(nameInBox, typeInBox, date);
//Second, we put this list in the model and set properties for jquery datatables
model.addObject("data", event);
//Verify id and info
System.out.println("The info is: " + event.getInfo());
System.out.println("The id is: " + event.getId());
//Finally, we return the model
return model;
}
When I try to execute, i got an org.springframework.dao.EmptyResultDataAccessExceptionIncorrect result size: expected 1, actual 0; but, if I query the DB via MySQL client, i can take the correct result without problems. So, there is a row that match the query I perform; this make me think that the problem is how I create the Json Object and/or I send it to Controller.
What's my error?
When sending informations with data, it's in the request's body, you can't retrieve your data with #RequestParam. You need to use #RequestBody and create and object with your three variables.
Example :
#PostMapping(value="/todaydatarecover.json")
#ResponseBody
public ModelAndView todayInfoAndIdRecover(#RequestBody TodayData todayData, ModelAndView model, HttpServletRequest request) throws IOException
{

Passing json data to a WebApi with special characters results to null

I have a json string that is being passed to a webapi, now the problem is, when I try adding special characters, the recieving object becomes null.
Here's I do it.
string json = JsonConvert.SerializeObject(ojectParams);
WebClient client = new WebClient();
client.Headers.Add("content-type", "application/json; charset=utf-8");
client.Headers.Add("AppKey", WebUser.AppKey);
client.Headers.Add("AppSecret", WebUser.AppSecret);
client.Headers.Add("AccountId", WebUser.AccountId.ToString());
if (!string.IsNullOrEmpty(WebUser.StoreId))
{
client.Headers.Add("StoreId", WebUser.StoreId);
}
var returnedStringObject = client.UploadString(string.Format("{0}/{1}", ConfigurationManager.AppSettings["Api"], endpoint), method, json);
Here's the json string:
"{\"Firstname\":\"kyv®\",\"Lastname\":\"sab®\"}"
I have added this one on the header hoping that it will fix the issue. But no luck with that.
charset=utf-8
On the recieving endpoint, the obj becomes null. But when I removed the special characters, the value is being passed.
[HttpPost]
public responseObj Endpoint(requestObj request)
Any ideas? Thanks!
You need to set the Encoding of the WebClient
client.Encoding = Encoding.UTF8;
Please see the code below.
Note: I did not use JsonConvert.SerializeObject and used HttpClient instead of WebClient
public static HttpRequestMessage CreateRequest(string requestUrl, HttpMethod method, String obj)
{
var request = new HttpRequestMessage
{
RequestUri = new Uri(requestUrl),
Method = method,
Content = new StringContent(obj, Encoding.UTF8, "application/json")
};
return request;
}
public static void DoAPI()
{
var client = new HttpClient();
var obj = "{\"Firstname\":\"kyv®\",\"Lastname\":\"sab®\"}";
var httpRequest = CreateRequest("mywebapiURL", HttpMethod.Post, obj);
var response = client.SendAsync(httpRequest).Result;
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}

SmartGWT RestDataSource JSON response text does not appear to be in standard response format

I have a web-based application with GWT 2.5.1, SmartGWT 4.0, Spring 3.2.3.Release, and Hibernate 4.1. The front-end uses a SmartGWT RestDataSource that passes data to RESTful web-service, a Spring MVC Controller, that passes data to the front end with Java.
The Controller is unit tested and works great, I use a GET to pass back the data in JSON, the controller calls the back-end, gets my data and I return a UserEntity back to the RestDataSource in JSON format.
The error is:
[ERROR] [TestAdmin] - 22:01:22.432:XRP8:WARN:RestDataSource:restLoginDS:RestDataSouce transformResponse(): JSON response text does not appear to be in standard response format.
I have done a lot of Googling, and looking on this site, and I can find people with similar issues, but no good solutions.
Here is the RestDataSource:
public class LoginDataSource extends RestDataSource
{
private static LoginDataSource instance = null;
public static LoginDataSource getInstance()
{
if (instance == null)
{
instance = new LoginDataSource("restLoginDS");
}
return instance;
}
private LoginDataSource(String id)
{
setID(id);
setClientOnly(false);
// set up FETCH to use GET requests
OperationBinding fetch = new OperationBinding();
fetch.setOperationType(DSOperationType.FETCH);
fetch.setDataProtocol(DSProtocol.GETPARAMS);
DSRequest fetchProps = new DSRequest();
fetchProps.setHttpMethod("GET");
fetch.setRequestProperties(fetchProps);
// set up ADD to use POST requests
OperationBinding add = new OperationBinding();
add.setOperationType(DSOperationType.ADD);
add.setDataProtocol(DSProtocol.POSTMESSAGE);
// ===========================================
DSRequest addProps = new DSRequest();
addProps.setHttpMethod("POST");
// addProps.setContentType("application/json");
add.setRequestProperties(addProps);
// set up UPDATE to use PUT
OperationBinding update = new OperationBinding();
update.setOperationType(DSOperationType.UPDATE);
update.setDataProtocol(DSProtocol.POSTMESSAGE);
// ===========================================
DSRequest updateProps = new DSRequest();
updateProps.setHttpMethod("PUT");
// updateProps.setContentType("application/json");
update.setRequestProperties(updateProps);
// set up REMOVE to use DELETE
OperationBinding remove = new OperationBinding();
remove.setOperationType(DSOperationType.REMOVE);
DSRequest removeProps = new DSRequest();
removeProps.setHttpMethod("DELETE");
remove.setRequestProperties(removeProps);
// apply all the operational bindings
setOperationBindings(fetch, add, update, remove);
init();
}
private DataSourceIntegerField userIdField; // "userId":"1",
private DataSourceTextField usernameField; // "username":"myusername",
private DataSourceTextField passwordField; // "password":"mypassword",
private DataSourceBooleanField userActiveField; // "active":true,
private DataSourceTextField fullnameField; // "fullname":"Thomas Holmes",
private DataSourceDateField birthdateField; // "birthdate":"1960-10-30",
private DataSourceTextField emailField; // "email":"myemail#test.net",
private DataSourceTextField cellPhoneField; // "cellPhone":"111-222-1234"
private DataSourceIntegerField updatedByField; // "updatedBy":1,
private DataSourceDateField updatedDateField; // "updatedDate":"2013-01-01",
private DataSourceIntegerField createdByField; // "createdBy":1,
private DataSourceDateField createdDateField; // "createdDate":"2013-01-01",
private DataSourceTextField securityQuestion1Field; // "securityQuestion1":"peanuts",
private DataSourceTextField securityAnswer1Field; // "securityAnswer1":"linus"
protected void init()
{
System.out.println("init: START");
setDataFormat(DSDataFormat.JSON);
setJsonRecordXPath("/");
// set the values for the datasource
userIdField = new DataSourceIntegerField(Constants.USER_ID, Constants.TITLE_USER_ID);
userIdField.setPrimaryKey(true);
userIdField.setCanEdit(false);
usernameField = new DataSourceTextField(Constants.USER_USERNAME, Constants.TITLE_USER_USERNAME);
usernameField.setCanEdit(false);
passwordField = new DataSourceTextField(Constants.USER_PASSWORD, Constants.TITLE_USER_PASSWORD);
passwordField.setCanEdit(false);
userActiveField = new DataSourceBooleanField(Constants.USER_ACTIVE, Constants.TITLE_USER_ACTIVE);
fullnameField = new DataSourceTextField(Constants.USER_FULLNAME, Constants.TITLE_USER_FULLNAME);
birthdateField = new DataSourceDateField(Constants.USER_BIRTHDATE, Constants.TITLE_USER_BIRTHDATE);
emailField = new DataSourceTextField(Constants.USER_EMAIL, Constants.TITLE_USER_EMAIL);
cellPhoneField = new DataSourceTextField(Constants.USER_CELL_PHONE, Constants.TITLE_USER_CELL_PHONE);
securityQuestion1Field =
new DataSourceTextField(Constants.USER_SECURITY_QUESTION_1, Constants.TITLE_USER_SECURITY_QUESTION_1);
securityAnswer1Field =
new DataSourceTextField(Constants.USER_SECURITY_ANSWER_1, Constants.TITLE_USER_SECURITY_ANSWER_1);
updatedByField = new DataSourceIntegerField(Constants.USER_UPDATED_BY, Constants.TITLE_USER_UPDATED_BY);
updatedDateField = new DataSourceDateField(Constants.USER_UPDATED_DATE, Constants.TITLE_USER_UPDATED_DATE);
createdByField = new DataSourceIntegerField(Constants.USER_CREATED_BY, Constants.TITLE_USER_CREATED_BY);
createdDateField = new DataSourceDateField(Constants.USER_CREATED_DATE, Constants.TITLE_USER_CREATED_DATE);
System.out.println("init: FINISH");
setFields(userIdField, usernameField, passwordField, userActiveField, emailField, cellPhoneField,
fullnameField, birthdateField, securityQuestion1Field, securityAnswer1Field, updatedByField,
updatedDateField, createdByField, createdDateField);
// setFetchDataURL(getServiceRoot() + "/userId/{id}");
// setFetchDataURL(getServiceRoot() + "/contactId/{id}");
setAddDataURL(getServiceRoot() + "/create");
setUpdateDataURL(getServiceRoot() + "/update");
setRemoveDataURL(getServiceRoot() + "/remove/{id}");
}
protected String getServiceRoot()
{
return "rest/login/";
}
protected String getPrimaryKeyProperty()
{
return "userId";
}
/*
* Implementers can override this method to create a different override.
*/
#SuppressWarnings("rawtypes")
protected void postProcessTransform(DSRequest request)
{
System.out.println("LoginDataSource: postProcessTransform: START");
StringBuilder url = new StringBuilder(getServiceRoot());
System.out.println("LoginDataSource: postProcessTransform: url=" + url);
Map dataMap = request.getAttributeAsMap("data");
System.out.println("LoginDataSource: postProcessTransform: dataMap=" + dataMap.toString());
if (request.getOperationType() == DSOperationType.FETCH && dataMap.size() > 0)
{
if (dataMap.get(Constants.USER_USERNAME) != null && dataMap.get(Constants.USER_PASSWORD) != null)
{
url.append("user/" + dataMap.get(Constants.USER_USERNAME));
url.append("/pwd/" + dataMap.get(Constants.USER_PASSWORD));
}
else if (dataMap.get(Constants.USER_USERNAME) != null && dataMap.get(Constants.USER_PASSWORD) == null)
{
url.append("user/" + dataMap.get(Constants.USER_USERNAME));
url.append("/pwd/" + dataMap.get(Constants.USER_PASSWORD));
}
else if (dataMap.get(Constants.USER_EMAIL) != null)
{
url.append("email/" + dataMap.get(Constants.USER_EMAIL));
}
}
System.out.println("LoginDataSource: postProcessTransform: url=" + url.toString());
request.setActionURL(URL.encode(url.toString()));
}
#Override
protected Object transformRequest(DSRequest dsRequest)
{
// now post process the request for our own means
postProcessTransform(dsRequest);
System.out.println("LoginDataSource: transformRequest: START");
dsRequest.setContentType("application/json");
JavaScriptObject jso = dsRequest.getData();
String jsoText = JSON.encode(jso);
System.out.println("LoginDataSource: transformRequest: START: jsoText=" + jsoText);
// this code is used only when there is a password change, otherwise this will be skipped
String userPassword = JSOHelper.getAttribute(jso, Constants.USER_NEW_PASSWORD);
if (userPassword != null)
{
// This creates the new JSON attribute:
// ... , "position":{"id":x}
JSOHelper.setAttribute(jso, "password", userPassword);
// remove the JSON Attribute: ... , "userPassword":"newPassword"
JSOHelper.deleteAttribute(jso, Constants.USER_NEW_PASSWORD);
}
System.out.println("LoginDataSource: transformRequest: FINISH: url=" + dsRequest.getActionURL());
String s1 = JSON.encode(jso);
System.out.println("LoginDataSource: transformRequest: FINISH: s1=" + s1);
return s1;
}
protected void transformResponse(DSResponse response, DSRequest request, Object jsonData)
{
System.out.println("LoginDataSource: transformResponse: START");
JavaScriptObject jsObj = (JavaScriptObject) jsonData;
String jsoText1 = JSON.encode(jsObj);
System.out.println("LoginDataSource: transformResponse: jsoText=" + jsoText1);
System.out.println("LoginDataSource: transformResponse: jsonData=" + jsonData.getClass());
for (String attr : response.getAttributes())
{
System.out.println("LoginDataSource: transformResponse: attr=" + attr + " value="
+ response.getAttribute(attr));
}
super.transformResponse(response, request, jsonData);
}
}
The error comes up on the line:
super.transformResponse(response, request, jsonData);
I know the data coming back from the Controller is JSON data as follows:
{
"userId":1,
"username":"my_username",
"password":"my_password",
"active":true,
"fullname":"Thomas Holmes",
"birthdate":"1960-10-13",
"email":"test#test.net",
"cellPhone":"111-222-1234",
"updatedBy":1,
"updatedDate":"2013-01-01",
"createdBy":1,
"createdDate":"2013-01-01",
"securityQuestion1":"peanuts",
"securityAnswer1":"linus"
}
I have tested that these names match the datasource fields in the json data.
We should be able to see that by checking the datasource fields above.
I have also unit tested with JUnit and Jackson Mapper 2.0 that the JSON string data can be used to create a UserDTO object and a UserEntity object.
I am very much aware of the SmartClient documentation about the data that comes back from a controller and how it must match the required format. This is a SmartGWT RestDataSource and I looked at the response which looks ok.
In the transformResponse code:
for (String attr : response.getAttributes())
{
System.out.println("transformResponse: attr=" + attr + " value="
+ response.getAttribute(attr));
}
Which yields:
transformResponse: jsonData=class com.google.gwt.core.client.JavaScriptObject$
transformResponse: attr=data value=[object Object]
transformResponse: attr=startRow value=0
transformResponse: attr=status value=0
transformResponse: attr=endRow value=1
transformResponse: attr=totalRows value=1
transformResponse: attr=httpResponseCode value=200
transformResponse: attr=transactionNum value=0
transformResponse: attr=clientContext value=null
transformResponse: attr=httpHeaders value=[object Object]
transformResponse: attr=context value=[object Object]
It looks like the "Object jsonData" is a JavaScriptObject.
Ultimately, the JSON that comes back, in a JavascriptObject, I'd like to convert to a UserDTO object.
So, if I can remove this error and solve this objective that would be great.
Thanks!
UPATE
I've been testing this out, and I finally have a small test app which I think shows that Isomorphic broke the RestDataSource in SmartGWT. I say that because my application was working before-hand, and now it doesn't work.
I confirmed hat all this is 100% valid JSON data. Running through various tests on the Net.
test1.json: {"userId":1}
test2.json: {"userId":"1"}
test3.json: [{"userId":1}]
test4.json: [{"userId":"1"}]
Then I isolated to a very small app to test. This is something similar to what is on the SmartGWT Showcase.
public class TestApp implements EntryPoint
{
private DataSourceIntegerField userIdField;
public void onModuleLoad()
{
RestDataSource dataSource = new RestDataSource();
dataSource.setDataFormat(DSDataFormat.JSON);
dataSource.setDataURL("data/single_user.json");
// set the values for the datasource
userIdField = new DataSourceIntegerField("userId", "User Id");
userIdField.setPrimaryKey(true);
userIdField.setCanEdit(false);
dataSource.setFields(userIdField);
ListGrid grid = new ListGrid();
grid.setDataSource(dataSource);
grid.setWidth100();
grid.setHeight(150);
grid.setAutoFetchData(true);
grid.draw();
}
}
In every case, I get the same error message:
[ERROR] [SoccerAdmin] - 15:20:55.945:XRP6:WARN:RestDataSource:isc_RestDataSource_0:RestDataSouce transformResponse(): JSON response text does not appear to be in standard response format.
However, if I change from a RestDataSource to a DataSource, then I don't have any issues with TransformResponse.
I guess maybe I don't know what TransformResponse is supposed to do with RestDataSource, but I did read the SmartClient Docs for what it's worth.
If I find a great workaround, then I will post an answer.
Ultimately I changed my LoginDataSource from extending RestDataSource to extending DataSource and all my issues went away.
Per the documentation, my response data was complete and accurate.
Also, my actual data was a valid JSON object and verified that against several sites.
Not sure what he bug with SmartGWT RestDataSource is, but I feel that it is a bug ... unless they can explain to me why it isn't.
Hope this helps someone else!

Read JSON with Jersey 2.0 (JAX-RS 2.0)

I was using Jersey 1.16 to consume a JSON, but now I'm with difficulties to consume a JSON using Jersey 2.0 (that implements JAX-RS 2.0).
I have a JSON response like this:
{
"id": 105430,
"version": 0,
"cpf": "55443946447",
"email": "maria#teste.br",
"name": "Maria",
}
and the method that consumes it:
public static JSONObject get() {
String url = "http://127.0.0.1:8080/core/api/person";
URI uri = URI.create(url);
final Client client = ClientBuilder.newClient();
WebTarget webTarget = client.target(uri);
Response response = webTarget.request(MediaType.APPLICATION_JSON).get();
if (response.getStatus() == 200) {
return response.readEntity(JSONObject.class);
}
}
I also tried:
return webTarget.request(MediaType.APPLICATION_JSON).get(JSONObject.class);
But the jSONObject return is null. I don't understand my error because the response is OK!
This is how to use the Response type correctly:
private void getRequest() {
Client client = ClientBuilder.newClient();
String url = "http://localhost:8080/api/masterdataattributes";
WebTarget target = client.target(url);
Response res = target
.request(MediaType.APPLICATION_JSON)
.get();
int status = res.getStatus();
String json = res.readEntity(String.class);
System.out.println(String.format("Status: %d, JSON Payload: %s", status, json));
}
If you're just interested in the payload, you could also just issue a get(String.class). But usually you will also want to check the response status, so working with the Response is usually the way to go.
If you want a typed (generic) JSON response, you could also have readEntity return a Map, or a list of Map if the response is an array of objects as in this example:
List<Map<String, Object>> json = res.readEntity(new GenericType<List<Map<String, Object>>>() {});
String id = (String) json.get(0).get("id");
System.out.println(id);
I have found the solution. Maybe it is not the best of, but it works.
public static JsonObject get() {
String url = "http://127.0.0.1:8080/core/api/person";
URI uri = URI.create(url);
final Client client = ClientBuilder.newClient();
WebTarget webTarget = client.target(uri);
Response response = webTarget.request(MediaType.APPLICATION_JSON).get();
//Se Response.Status.OK;
if (response.getStatus() == 200) {
StringReader stringReader = new StringReader(webTarget.request(MediaType.APPLICATION_JSON).get(String.class));
try (JsonReader jsonReader = Json.createReader(stringReader)) {
return jsonReader.readObject();
}
}
return null;
}
I switched the class JSONObject (package import org.codehaus.jettison) by JsonObject (package javax.json) and I used the methods to manipulate the content as String.
S.
mmey answer is the correct and optimal one, instead of invoking the service twice it does it one time.