GZIP JSON AJAX response text is empty - ajax

I am facing a problem, while encoding the response that I send back for an AJAX request, using GZIP. Can anyone give me some pointers on this please?
There is an AJAX request from the JSP,
An action class (Struts) at the server side handles the request,
The response is prepared as a JSON object,
The JSON string is written to the Response object and sent back,
the JSON string is read from the responseText property of the xmlHttp object back at the jsp
This works fine. However, instead of sending the raw JSON data, if I send back encoded JSON data, then there are issues.
Server Side Code to create GZip'ed JSON :
// jsonStr = JSONObj.toString();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(bos);
gzip.write(jsonStr.getBytes());
gzip.close();
String newStr = new String(bos.toByteArray());
// set the response header and send Encoded JSON response
response.setHeader("Content-Type", "application/json");
response.setHeader("Content-Encoding", "gzip");
response.setHeader("Vary", "Accept-Encoding");
pw = response.getWriter();
pw.write(newStr);
pw.close();
At the JSP :
// marker
alert('Length of the received Response Text : ' + xmlHttp.responseText.length);
// evaluate the JSON
jsonStr = eval('(' + xmlHttp.responseText + ')');
The alert box, on receiving the response, reports length as 0!

Related

ASP.NET authorization using RestSharp

On the site "example.net" I have standart api method to take access token (which i can call /Token) and if I make POST request using Fiddler to example.net/Token with parameters in request body
And all is OK. Status code 200 and in the response access token and other info.
But if I do this request from other site using RestSharp - 500 Internal Server Error. I tried to AddParameter, AddBody, AddObject. Make parameters as a JSON string, to change DataFormat, to AddHeader of Content-Type. This is my last version of request.
request = new RestRequest(URL, Method.POST);
//request.AddHeader("Content-Type", ContentType);
string UrlEncoded = "";
//I parse Parameters to format like I use in request body in Fiddler.
if (Parameters.Count != 0)
foreach (var param in Parameters)
UrlEncoded = param.ParamToUrlEncoded(UrlEncoded);
request.AddBody(UrlEncoded);
IRestResponse response = client.Execute(request);
var content = response.Content;
Do i need to set any more attributes on the request or something?
Thank you.

Globally formatting .net Web Api response

I have a Web Api service that retrieves data from another service, which returns Json. I don't want to do anything to the response, I just want to return it directly to the client.
Since the response is a string, if I simply return the response, it contains escape characters and messy formatting. If I convert the response in to an object, the WebApi will use Json.Net to automatically format the response correctly.
public IHttpActionResult GetServices()
{
var data = _dataService.Get(); //retrieves data from a service
var result = JsonConvert.DeserializeObject(data); //convert to object
return Ok(result);
}
What I would like is to either A: Be able to return the exact string response from the service, without any of the escape characters and with the proper formatting, or B: Set a global settings that will automatically Deserialize the response so that the Web Api can handle it the way I am doing it already.
On Startup I am setting some values that describe how formatting should be handled, but apparently these aren't correct for what im trying to do.
HttpConfiguration configuration = new HttpConfiguration();
var settings = configuration.Formatters.JsonFormatter.SerializerSettings;
settings.Formatting = Formatting.Indented;
settings.ContractResolver = new DefaultContractResolver();
Do I need to create a custom ContractResolver or something? Is there one that already handles this for me?
Thanks
If you want to just pass through the json (Option A), you can do this
public IHttpActionResult GetServices() {
var json = _dataService.Get(); //retrieves data from a service
HttpContent content = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json");
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = content;
return ResponseMessage(response);
}

GZip .NET Compact Framework 3.5

I am trying to send and receive process gzip-ed data from server on my client device application (not web).
I am sending gzip-ed content and on client side, I have following method that returns WebResponse:
protected override WebResponse GetWebResponse(WebRequest request)
{
WebResponse res = base.GetWebResponse(request);
if (((System.Net.HttpWebResponse)(res)).ContentEncoding.Contains("gzip"))
{
Stream responseStream = res.GetResponseStream();
responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
}
//This returns g-ziped content as WebResponse, but I need to return
//above decompressed responseStream as WebResponse, how do I do that?
return res;
}
I am new to this but I am thinking that intercepting every response comming to my app in GetWebResponse is excellent centralized spot to decompress all responses. But the problem is how to pass the decompressed stream as response back?
Much appreciated

Redirect JSF ajax request to an URL with request parameters in a servlet filter

I am using JSF2.2 and have servlet filter configured. Part of the code in Filter that work:
HttpServletResponse response = (HttpServletResponse) resp;
if (userSession == null) {
redirectURLRegular = response.encodeRedirectURL("../login.xhtml?param1=noSession");
redirectURLAjax = response.encodeRedirectURL(request.getContextPath()
+ "/faces/login.xhtml?param1=noSession");
else{
chain.doFilter(req, resp);
return;
if (isAJAXRequest(request)) {
StringBuilder sb = new StringBuilder();
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<partial-response><redirect url=\"").append(redirectURLAjax)
.append("\"></redirect></partial-response>");
response.setHeader("Cache-Control", "no-cache");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/xml");
PrintWriter pw = response.getWriter();
pw.println(sb.toString());
pw.flush();
} else {
response.sendRedirect(redirectURLRegular);
}
If session is null redirect - both regular and AJAX happens. In next page (login.xhtml, requestScoped) I can get parameter value (param1) in bean via
#ManagedProperty("#{param.param1}")
private String param1;
If I add second param "../login.xhtml?param1=noSession&param2=val2" - regular requests work (redirect happens and see both params) but AJAX request dose not work(no redirect, nothing happens). Here is Firebug report:
XML Parsing Error: not well-formed Location: moz-nullprincipal:{4584d37a-e799-43db-8379-b0451edca95c} Line Number 1, Column 120:
..."/admin/faces/login.xhtml?param1=noSession&param2=val2"></redirect></partial-r...
...-------------------------------------------------^
How is this caused and how can we set multiple parameters in filter for AJAX calls?
The & is a special character in XML representing the start of an entity like &, <, etc. The XML parser is implicitly looking for the name (amp, lt, etc) and the ending ;. However, you wasn't using it as such and hence the webbrowser's XML parser felt over it when it unexpectedly encountered an =, making it non-well-formed XML.
You need to escape the XML special character & into the entity &.
redirectURLAjax = response.encodeRedirectURL(request.getContextPath()
+ "/faces/login.xhtml?param1=noSession&param2=val2");

Attempting to test rest service with multipart file

I am attempting to test a rest service I created. The service is a post.
I wanted to create a file to pass the parameters(including a multi-part file).
From there I am trying to call the service at this point.
Pretty sure the service that doesn't work. But when I call rest Service. I have a simple form that just passes in a couple values including the jpg.
Here is the code.
HttpMessageConverter bufferedIamageHttpMessageConverter = new ByteArrayHttpMessageConverter();
restTemplate.postForObject("http://localhost:8080/sendScreeenAsPostCard", uploadItem.getFileData(), String.class));
My method signature is:
ResultStatus sendScreenAsPostcard( #RequestParam MultipartFile image, #RequestParamString userId)
That is the error I am getting.
Could not write request: no suitable HttpMessageConverter found for request type [org.springframework.web.multipart.commons.CommonsMultipartFile]
You need to simulate a file upload, which requires a particular content type header, body parameters, etc. Something like this should do the trick:
// Fill out the "form"...
MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<String, Object>();
parameters.add("file", new FileSystemResource("file.jpg")); // load file into parameter
parameters.add("blah", blah); // some other form field
// Set the headers...
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "multipart/form-data"); // we are sending a form
headers.set("Accept", "text/plain"); // looks like you want a string back
// Fire!
String result = restTemplate.exchange(
"http://localhost:8080/sendScreeenAsPostCard",
HttpMethod.POST,
new HttpEntity<MultiValueMap<String, Object>>(parameters, headers),
String.class
).getBody();

Resources