How can I get the json file from ResponseEntity? - json

I have my web service consuming another web service. in my web service I modify some fields of the json. then in postman it is consumed ok.
Now I need to convert the ResponseEntity to a .json file to save it to a folder on my computer, but the attempt has failed.
Any ideas?
my controller current:
#Controller
public class SiviccController {
private final Logger log = LoggerFactory.getLogger(SiviccController.class);
private String url = "http://localhost:9090/url_1";
#GetMapping("/url_2")
#ResponseBody
public Body sivicc() {
RestTemplate restTemplate = new RestTemplate(Factory.timeoutHttp());
try {
return restTemplate.getForObject(url, Body.class);
} catch (Exception e) {
Body body = new Body();
body.setIserror(true);
log.info(e.getMessage());
return body;
}
}
}
Matheus Cirillo works perfectly with the following code:
#Controller
public class SiviccController {
private final Logger log = LoggerFactory.getLogger(SiviccController.class);
private String url = "http://localhost:9090/url_1";
#GetMapping("/url_2")
#ResponseBody
public Body sivicc() {
RestTemplate restTemplate = new RestTemplate(Factory.timeoutHttp());
try {
String response = restTemplate.getForObject(url, String.class);
BufferedWriter writer = new BufferedWriter(new FileWriter("my-file.json", true));
writer.append(response);
writer.close();
return restTemplate.getForObject(url, Body.class);
} catch (Exception e) {
Body body = new Body();
body.setIserror(true);
log.info(e.getMessage());
return body;
}
}
}
However, the web service that you were consuming before now generates a token. That's why I change getForObject to exchange and I consume it well, but I apply the same logic to save the json in a folder on my computer, but it generates a failure in two lines:
#Controller
public class SiviccController {
private final Logger log = LoggerFactory.getLogger(SiviccController.class);
private String url = "http://localhost:9090/url_1";
#GetMapping("/url_2")
#ResponseBody
public Body sivicc() {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.set("Authorization", "bearer 8P7oM_ZDhB3TYolVkB1MLtM734DrrUSMVEFuiy3u");
HttpEntity request = new HttpEntity(headers);
headers.add("User-Agent", "Spring's RestTemplate" );
ResponseEntity<String> response = restTemplate.exchange(
url,
HttpMethod.GET,
request,
//Body.class,
String.class,
1
);
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("my-file.json", true));
writer.append(response);//Error: The method append(CharSequence) in the type Writer is not applicable for the arguments (ResponseEntity<String>)
writer.close();
return response.getBody();//Error: Type mismatch: cannot convert from String to Body
} catch (Exception e) {
Body body = new Body();
body.setIserror(true);
log.info(e.getMessage());
return body;
}
}
}

Change the Response type from getForObject to String.class, then, use the BufferedWriter to write the file.
RestTemplate rest = new RestTemplate();
String response = rest.getForObject("http://example.com/", String.class);
BufferedWriter writer = new BufferedWriter(new FileWriter("my-file.json", true));
writer.append(response);
writer.close();
Edit
The RestTemplate#exchange returns a ResponseEntity<T>, not a String.
In your case, it will return a ResponseEntity<String>.
That's why you're unable to write the object. To do so, you need to get the body from the ResponseEntity object. Use the method ResponseEntity#getBody
Something like this:
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, request, String.class, 1);
BufferedWriter writer = new BufferedWriter(new FileWriter("my-file.json", true));
// here you are getting the String with the response.getBody() method,
// so buffered writer can write the file
writer.append(response.getBody());
writer.close();

Resolved:
add to pom.xml:
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
</dependencies>
Use the Jackson API ObjectMapper class to convert Java Object to a JSON string
Use the BufferedWriter to write the file. #Matheus Cirillo
ObjectMapper mapper = new ObjectMapper();
try {
json = mapper.writeValueAsString(response.getBody());
System.out.println("ResultingJSONstring = " + json);
BufferedWriter writer = new BufferedWriter(new FileWriter("my-file.json", true));
writer.append(json);
writer.close();
} catch (JsonProcessingException e) {
e.printStackTrace();
}
thanks for your help =)

Related

How to send data from libgdx project to web?

I would like to work on moving the json data from libgdx to my web server, but I am not sure how to do it. The method below was created by referring to libgdx's documentation.
private void httpPostJson(){
final Json json = new Json();
final String requestJson = json.toJson(requestObject);
Net.HttpRequest request = new Net.HttpRequest("POST");
final String url = "http://localhost:8080/data";
request.setUrl(url);
request.setContent(requestJson);
request.setHeader("Content-Type", "application/json");
Gdx.net.sendHttpRequest(request, new Net.HttpResponseListener() {
#Override
public void handleHttpResponse(Net.HttpResponse httpResponse) {
String responseJson = httpResponse.getResultAsString();
Gson gson = new Gson();
data = gson.fromJson(responseJson, Person.class);
//'Person' is just sample class. data is class Person's object.
data.StoreData("",1);//successed to receive json data from web server.
//StoreData is just getter method.
}
#Override
public void failed(Throwable t) {
Gdx.app.log("failed!");
}
#Override
public void cancelled() {
Gdx.app.log("cancelled!");
}
});
}
It is possible to receive data transmitted from a web server.
But, this method can't send data to web server.
Can you tell me how to move data from libgdx project to web server?
This is the data transmitted to the web server:
final String requestJson = json.toJson(requestObject);
We are using the following Code (as you have more control over the request as opposed to using gdx.net), works like a charm, just don't execute on the main thread - body is your JSON as String
URL url = new URL(<your url>);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type",
"application/json; charset=utf-8");
if (body != null) {
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
os, "UTF-8"));
writer.write(body);
writer.close();
os.close();
}
conn.connect();
String s = stringFromStream(conn.getInputStream(), 4096);
Method stringFromStream:
public static String stringFromStream(final InputStream is,
final int bufferSize) {
final char[] buffer = new char[bufferSize];
final StringBuilder out = new StringBuilder();
try {
final Reader in = new InputStreamReader(is, "UTF-8");
try {
for (; ; ) {
int rsz = in.read(buffer, 0, buffer.length);
if (rsz < 0)
break;
out.append(buffer, 0, rsz);
}
} finally {
in.close();
}
} catch (Exception ex) {
}
return out.toString();
}

Mocking a RestTemplate and return object based in json file in Spring v1.5.14.RELEASE

I have this RestTemplate that I want to mock and return an object based on a json file
ResponseEntity<List<Hotel>> deliveryResponse =
restTemplate.exchange(link.getHref(),
HttpMethod.GET, null, new ParameterizedTypeReference<List<Hotel>>() {
});
the mock I try:
when(restTemplate.exchange(eq("delivery"), eq(HttpMethod.GET), any(), eq(Object.class)))
.thenReturn(readObjectFromFile("hotel.json", Order.class));
and
private <T> T readObjectFromFile(final String fileName, final Class<T> clazz) {
ObjectMapper objectMapper = new ObjectMapper();
try {
return objectMapper.readValue(this.getClass().getClassLoader().getResourceAsStream("__files/" + fileName), clazz);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
but I have this compilation error:
Cannot resolve method 'thenReturn(T)'
I think you got a typo?
Try this.
when(restTemplate.exchange(eq("delivery"), eq(HttpMethod.GET), any(), eq(Object.class)))
.thenReturn(readObjectFromFile("hotel.json"), Order.class);

How to send JSON data in request to rest web service

I have created a rest webservice which has a below code in one method:
#POST
#Path("/validUser")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public JSONObject validUserLogin(#QueryParam(value="userDetails") String userDetails){
JSONObject json = null;
try{
System.out.println("Service running from validUserLogin :"+userDetails);
json = new JSONObject(userDetails);
System.err.println("UserName : "+json.getString("userName")+" password : "+json.getString("password"));
json.put("httpStatus","OK");
return json;
}
catch(JSONException jsonException) {
return json;
}
}
I am using Apache API in the client code.And below client code is calling this service, by posting some user related data to this service:
public static String getUserAvailability(String userName){
JSONObject json=new JSONObject();
try{
HttpContext context = new BasicHttpContext();
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
URI uri=new URIBuilder(BASE_URI+PATH_VALID_USER).build();
HttpPost request = new HttpPost(uri);
request.setHeader("Content-Type", "application/json");
json.put("userName", userName);
StringEntity stringEntity = new StringEntity(json.toString());
request.setEntity(stringEntity);
HttpResponse response = client.execute(request,context);
System.err.println("content type : \n"+EntityUtils.toString(response.getEntity()));
}catch(Exception exception){
System.err.println("Client Exception: \n"+exception.getStackTrace());
}
return "OK";
}
The problem is, I am able to call the service, but the parameter I passed in the request to service results in null.
Am I posting the data in a wrong way in the request. Also I want to return some JSON data in the response, but I am not able to get this.
With the help of Zack , some how i was able to resolve the problem,
I used jackson-core jar and changed the service code as below.
#POST
#Path("/validUser")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public JSONObject validUserLogin(String userDetails){
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readValue(userDetails, JsonNode.class);
System.out.println("Service running from validUserLogin :"+userDetails);
System.out.println(node.get("userName").getTextValue());
//node.("httpStatus","OK");
return Response.ok(true).build();
}

HTTP error 500 on Android

So here is my code, its purpose is to fecth a json file. I get an error 500 from the server, which means I know that it is an internal server error. As I can't access to the logs of the the server, I'm pretty much stuck from now... I read about session and cookies, maybe that's it. What do you guy think of it ?
private class ListingFetcher extends AsyncTask<Void, Void, String> {
private static final String TAG = "ListingFetcher";
public static final String SERVER_URL = "http://www.myurl.com/listing.json";
#Override
protected String doInBackground(Void... params) {
try {
//Create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(SERVER_URL);
//Perform the request and check the status code
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
try {
//Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
List<Listing> events = new ArrayList<Listing>();
events = Arrays.asList(gson.fromJson(reader, Listing[].class));
content.close();
handlePostsList(events);
} catch (Exception ex) {
Log.e(TAG, "Failed to parse JSON due to: " + ex);
failedLoadingPosts();
}
} else {
Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
failedLoadingPosts();
}
} catch(Exception ex) {
Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
failedLoadingPosts();
}
return null;
}
}
My code is perfectly working. THe only mistake is on this line :
HttpPost post = new HttpPost(SERVER_URL);
Which should be
HttpGet get = new HttpGet(SERVER_URL);

return ModelAndView when JSON is returned

Can we return JSON object from spring controller and write that JSON object on jsp page.
Below is my jsp page:
<script type="text/javascript">
dojo.require("dojox.grid.EnhancedGrid");
dojo.require("dojox.data.QueryReadStore");
dojo.ready(function(){
mystore=new dojo.data.ItemFileReadStore({url:"<%=request.getContextPath()%>/showData.htm"});
var layout= [
{field: 'ID', name: 'SID',formatter: hrefFormatter,datatype:"number" },
{field: 'SPREAD',name: 'SPREAD',autoComplete: true}
]
var grid = new dojox.grid.EnhancedGrid({
id: 'myGrid',
----
});
</script>
Controller:
#RequestMapping(value = "/showData", method = RequestMethod.GET)
public void getSTIDData(HttpServletRequest request,
HttpServletResponse response, #ModelAttribute VINDTO vinData,
BindingResult beException) throws IOException {
try {
......
......
XStream xstream = new XStream(new JsonHierarchicalStreamDriver() {
public HierarchicalStreamWriter createWriter(Writer writer) {
return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE);
}
});
xstream.alias("items", com.loans.auto.DTO.VINRequestDTO.class);
String str = xstream.toXML(vinListCopy);
StringBuffer rowData = new StringBuffer();
rowData.append("{'numRows':").append(vinListCopy.size())
.append(",'items':").append(str).append("}");
PrintWriter out = response.getWriter();
out.print(rowData);
}
Instead of getSTIDData(..) returning void , i want this method to return ModelAndView object, but when i return ModelAndView object, in jsp page data is not getting loaded and it says "NO Data Found". Please suggest. Thanks.
Below is the exception generated when i used Gson
SyntaxError {stack: "SyntaxError: Unexpected identifier↵ at Object.d… at signalWaiting (/MYWebProject/dojo/Deferred.js:28:4)", message: "Unexpected identifier"}
message: "Unexpected identifier"
stack: "SyntaxError: Unexpected identifier↵ at Object.dojo.fromJson (/MYWebProject/dojo/_base/json.js:26:23)↵ at Object.dojo._contentHandlers.dojo.contentHandlers.json (/MYWebProject/dojo/_base/xhr.js:78:16)↵ at Object.dojo._contentHandlers.dojo.contentHandlers.json-comment-optional (/MYWebProject/dojo/_base/xhr.js:156:28)↵ at _deferredOk (/MYWebProject/dojo/_base/xhr.js:432:42)↵ at notify (/MYWebProject/dojo/_base/Deferred.js:187:23)↵ at complete (/MYWebProject/dojo/_base/Deferred.js:168:4)↵ at resolve.callback (/MYWebProject/dojo/_base/Deferred.js:248:4)↵ at eval (/MYWebProject/dojo/_base/xhr.js:627:8)↵ at signalListener (/MYWebProject/dojo/Deferred.js:37:21)↵ at signalWaiting (/MYWebProject/dojo/Deferred.js:28:4)"
__proto__: Error
yes you can return as JSON response.showing with the help of Gson API
#RequestMapping(value = "/showData", method = RequestMethod.GET)
public #ResponseBody String getUserHomePage(HttpServletRequest request,HttpServletResponse response, #ModelAttribute VINDTO vinData,BindingResult beException) throws IOException {
//you code stuff to create model object bean
Gson gson = new Gson();
return gson.toJson(objectBean);
}
Keep it clean and simple...
Here is a real life snippet of code ...
#RequestMapping(value = "/actions/getImplGroups", method = RequestMethod.POST)
public ResponseEntity<String> getImplGroups(HttpServletRequest request, HttpServletResponse response) {
List<String> groups = bpmClient.getAllGroups();
ObjectMapper mapper = new ObjectMapper();
String jsonString;
try {
jsonString = mapper.writeValueAsString(groups);
} catch (JsonGenerationException e) {
jsonString = "Error with json generation: " + e.getMessage();
} catch (JsonMappingException e) {
jsonString = "Error with json mapping: " + e.getMessage();
} catch (IOException e) {
jsonString = "Error with json: " + e.getMessage();
}
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<String>(jsonString, responseHeaders, HttpStatus.CREATED);
}
The important point to consider is sending the correct web header, so that your page expects to see json.
I the case above we used the Jackson library to create the json, but in truth you could format the json any way you like. Here is an example of a simple, manually formatted string...
#RequestMapping(value = "/actions/getTicketsNotUpdatedWithinShift", method = RequestMethod.POST)
public ResponseEntity<String> getTicketsNotUpdatedWithinShift(String center, String sections, String minutesInShift, Model model) {
String[] sectionArray = sections.split(",");
String json = "";
String rowsString = "";
for (String section : sectionArray) {
List<Map<String, String>> rows = service.getMinutesSinceLastTicketUpdate(center, section);
for (Map<String, String> row : rows) {
int minutesSinceUpdate = Integer.parseInt(row.get("minutes"));
if (minutesSinceUpdate > Integer.parseInt(minutesInShift)) {
String description = row.get("description");
rowsString = rowsString + "\"" + description + "\",";
}
}
}
// Build the json structure
if (!rowsString.isEmpty()) {
// Trim the trailing comma.
rowsString = rowsString.replaceAll(",$", "");
json = "[" + rowsString + "]";
} else {
json = "[]";
}
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED);
}