I do have get request over http from an angular based client side which expects as an answer an array of bytes from a java server.
angular.ts
downloadDocument(documentId: string) {
const params = new HttpParams().set('docId', documentId);
return this.httpClient.get<any>(`/downloadpdf/`,
{ params: params});
}
controller.java
#GetMapping("/downloadpdf")
public String downloadDocument(#RequestParam("docId") final String docId) {
String response = (new String(getBytesArray(docId)));
// getBytesArray returns a byte[]
// response correctly computed
return response;
}
Parsing error is encountered while transmitting over http:
"HttpErrorResponse":
message: 'Http failure during parsing for http://localhost...'
error: 'error: SyntaxError: Unexpected token % in JSON at position 0 at JSON.parse () at XMLHttpRequest.onLoad'
Any ideas why this is happening?
It's happening because you call the overload of get() that takes a generic parameter:
this.httpClient.get<any>(...)
This overload sets the response type to JSON, thus telling the HttpClient to parse the response body to JSON and to returned the generated object or array. Since you do not want to receive JSON, you must use another overload.
The documentation is your friend.
If you want to receive a Blob, for example, you would use the second overload, documented as returning an Observable<Blob>, and expecting options with responseType: 'blob'.
Related
I am trying to automate twitter API. when tried to print "js.get("text") using
System.out.println(js.get("text")); I am getting error as
"The method println(boolean) is ambiguous for the type PrintStream"
I downloaded jars and passed in Build path as well "scribejava-apis-2.5.3" and "scribejava-core-4.2.0"
Below code is not allowing me use println for ------>js.get("text")
public class Basicfunc {
String Consumerkeys= "**************";
String Consumersecretkeys="*******************";
String Token="*******************";
String Tokensecret="***************************";
#Test
public void getLatestTweet(){
RestAssured.baseURI = "https://api.twitter.com/1.1/statuses";
Response res = given().auth().oauth(Consumerkeys, Consumersecretkeys, Token, Tokensecret).
queryParam("count","1").
when().get("/home_timeline.json").then().extract().response();
String response = res.asString();
System.out.println(response);
JsonPath js = new JsonPath(response);
System.out.println(js.get("text"));
}
}
Use System.out.println(js.getString("text")); instead of System.out.println(js.get("text"));, because get returns any primitive value.
I think your problem is that your twitter response is actually a list.
Try to use System.out.println(js.getList()[0].get("text")); and be aware that you are only using the first [0] entry and ignoring the rest.
I'm very new to this, like really, really new.
I'm using Spring MVC (5.0) and am making an ajax call, as shown below.
This all works fine.
#RestController
public class AjaxController
{
#RequestMapping(value="/search/users", method=RequestMethod.GET)
public Person getUsers(#RequestParam("username") String username)
{
persons = personService.findPersonByUsername(username);
return persons.size() == 0 ? null : persons.get(0);
}
}
The method gets the person from the database and returns it.
According to the Spring Restful guide,
"The XXX object must be converted to JSON.Thanks to Spring’s HTTP message converter support, you don’t need to do this conversion manually. Because Jackson 2 is on the classpath, Spring’s MappingJackson2HttpMessageConverter is automatically chosen to convert the XXX instance to JSON."
So, Spring is automatically generating the JSON which will be returned to the client. The problem is, I get an error message in my client javascript:
SyntaxError: JSON.parse: unterminated string literal at line 1 column 103911 of the JSON data
My client javascript is equally simple, consisting of only:
function ajax_get_users(input_box)
{
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "users?username=" + username, true); // url of server-side ajax script, specify synchronous ajax call
// get asynchronous response
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var person = JSON.parse(this.responseText); // this is where the unterminated String error occurs
}
};
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // set http header
xhttp.send(); // send the ajax request to the web server
}
Since Spring is constructing the JSON, how do I even fix the problem?
I'm using the SoapUI API as part of an existing java project.
The application should save the request and response XML in an specific report file.
I wonder if it's possible to get those requests and responses via the API.
The method invoking the TestCaseRunner looks like this
protected void checkTestCase(TestCase testCase) {
TestCaseRunner tr = testCase.run(null, false);
for (TestStepResult tcr : tr.getResults()) {
String status = tcr.getStatus();
String time = tcr.getTimeTaken() + "ms";
/* How to get XML messages?
* String request =
* String response =
*/
}
}
Depending on exactly what kind of test steps you have they might be an instance of a MessageExchange. Casting the TestStepResult to a MessageExchange and calling getRequestContent / getResponseContent might do the trick.
String request = ((MessageExchange)tcr).getRequestContent();
String response = ((MessageExchange)tcr).getResponseContent();
I have used the following way to get the response from the API CAll performed:
runner = testRunner.runTestStepByName("Your Test Case name");
// Here we take the response in ms of the API call
timeTaken = runner.response.timeTaken;
// here we get the HTTP response code.
responseCode = runner.getResponseHeaders()."#status#";
// here we get the response content
String response = runner.getResponseContent();
// here we get the API call endpoint -> in case you need to print it out.
String endPoint = runner.getEndpoint();
this is my servlet code
List<Group> list= dao.findgroup(user);
JSONObject json=(JSONObject) JSONSerializer.toJSON(list);
ServletResponse response=ActionContext.getServletResponse();
response.setContentType("text/JSON");
PrintWriter out=response.getWriter();
out.println(json);
out.close();
//this is my jquery code
$.get("viewgroup.process",function(data){
var use=$.parseJSON(data);
$(use).each(function(i,v)
{
var det="<tr><td>"+v.value+"</td><td>"+v.description+"</td><td>"+v.code+"</td><td>"+v.status+"</td><td><a href='#'>reset code</a></td><td><a href='#'>change status</a></td></tr>";
$(det).appendTo("#tablebody");
});
Now my problem is when i am sending this request and getting a list as json object,and when I use method parseJSON it gives me error:
SyntaxError: JSON.parse: unexpected character
Can any one tell me why this error is there?
Pretty sure the data parameter when using $.get is already a javascript object (rather than a JSON string), so no need to parse it again:
$.get("viewgroup.process",function(data){
var use = data;//or just use data directly rather that a new variable called use
$(use).each(function(i,v)
{
var det="<tr><td>"+v.value+"</td><td>"+v.description+"</td><td>"+v.code+"</td><td>"+v.status+"</td><td><a href='#'>reset code</a></td><td><a href='#'>change status</a></td></tr>";
$(det).appendTo("#tablebody");
});
//rest of code...
});
Change out.println(json); to out.println(json.toString()); in your servlet code. You want to send out the stringified JSON, not the actual object.
http://www.json.org/javadoc/org/json/JSONObject.html#toString%28%29
I have this method :
#GET
#Path("/myservice")
#Produces(MediaType.APPLICATION_JSON)
public Response mysercice() {
boolean userExists = false;
CacheControl cacheControl = new CacheControl();
cacheControl.setNoCache(true);
cacheControl.setNoStore(true);
JSONObject jsonObject = new JSONObject();
jsonObject.put("userExists", userExists);
return Response.ok(jsonObject, MediaType.APPLICATION_JSON).cacheControl(cacheControl).build();
}
When accessing to the URL of the method in the browser, I get { }, it means that the object is empty.
So, I tried to use :
return Response.ok(jsonObject.toString(), MediaType.APPLICATION_JSON).cacheControl(cacheControl).build();
So, I get in the browser {"userExists" : false}
But I didn't understand why when returning simply the JSONObject, we get in the browser an empty object.
Most JAX-RS implementations come with a provider for mapping response entities to JSON. So when you write:
return Response.ok(jsonObject, MediaType.APPLICATION_JSON).build();
You are basically requesting that the JAX-RS provider marshall the JSONObject into JSON for you. The only problem being that JSONObject isn't really meant to be serialized this way. Instead its meant to be used to build a JSON representation incrementally, then convert that representation into a JSON string value. You have two options:
Create a POJO containing all the fields you want to send back to the client. Return this POJO in your method and it will be automatically converted to JSON (`return Response.ok(myPojo, MediaType.APPLICATION_JSON).build()
Return the JSON data directly as a String (which you already did in your example that works).