I started developing a webinterface with bootstrap and so I used javascript to receive some JSON-Data.
My JSON-String is build with JSONObjects in JAVA and I used Jersey RestFUL-Service.
Java Code:
#GET
#Path("test")
#Produces(MediaType.TEXT_HTML)
public String createTestJson(){
JSONObject jsobject= new JSONObject();
try {
jsobject.append("test1", "test");
jsobject.append("test2", "test");
jsobject.append("test3", "test");
jsobject.append("test4", "test");
jsobject.append("test5", "test");
jsobject.append("test6", "test");
jsobject.append("test7", "test");
}catch(Exception e){
e.printStackTrace();
}
return jsobject.toString();
}
When I call the URL with the browser it works:
{"test1":["test"],"test2":["test"],"test3":["test"],"test4":["test"],"test5":["test"],"test6":["test"],"test7":["test"]}
I created a JavaScript function, which should retrieve the JSON String and fill the certain values in my HTML-page.
function loadJSON()
{
var data_file = "http://127.0.0.1:8085/Rest/test/test";
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 )
{
alert(http_request.responseText.length);
var jsonObj = JSON.parse(http_request.responseText);
document.getElementById("test1").innerHTML = jsonObj.test1;
document.getElementById("test2").innerHTML = jsonObj.test2;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
When I analyse the document with firebug, I can see that the GET- inquiry is completed and it's state is "200 OK". The answer of the inquiry is the JSON String.
I also analysed the script and it seems to stop working at:
var jsonObj = JSON.parse(http_request.responseText);
Additionally I wrote out the length of the responseText and the result is "0".
So I really don't get the problem. According firebug the script gets the data, but it breaks down at parsing the JSON String. It could relate to the responseText, which has a length of 0.
-------Edit-----
More Firebug information:
The XMLHTTPRequest-Object Data after receiving the data:
DONE 4
HEADERS_RECEIVED 2
LOADING 3
OPENED 1
UNSENT 0
mozAnon false
mozBackgroundRequest false
mozSystem false
onloadend null
ontimeout null
readyState 1
response ""
responseText ""
responseType ""
responseXML null
status 0
statusText ""
timeout 0
The inquiry-header
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language de-de,de;q=0.8,en-us;q=0.5,en;q=0.3
Connection keep-alive
Host 127.0.0.1:8085
Origin null
User-Agent Mozilla/5.0 (Windows NT 6.3; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0
The response-header
Content-Type application/xhtml+xml
Date Mon, 24 Aug 2015 22:56:18 GMT
Server Apache-Coyote/1.1
Transfer-Encoding chunked
Response:
{"test1":["test"],"test2":["test"],"test3":["test"],"test4":["test"],"test5":["test"],"test6":["test"],"test7":["test"]}
Maybe you can help me!
Thank you!
Marko
I would be interested if your JSON is recieved as type="application/json or perhaps as XML/HTML. Could it be that the response is XML and so the "object" is stored inside http_request.XML?
---------- EDIT ----------
I think you are having issues with the Same-Origin-Policy of JS. You cannot load your field because of that. Try to implement your JS inside a view of your Java-App (so that you can access it via http:// and in the same domain as your app) and try it again.
Related
This is my very first question I am posting on StackOverflow. I usually tend to find answers to any question I have for whatever project, but I am really stuck on this one. I'm writing a Chrome extension that attempts to send JSON-objects over a HTTP post request with certain data in it to a basic Java server that will -in a later stage- process some of the data and return a HTTP response with relevant (processed) information for the client. This is the relevant JavaScript snippet on client-side:
function postRequest(jsonObject) {
var param = JSON.stringify(jsonObject);
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState == 4) {
console.log(request.response);
}
};
request.open("POST", "http://"+link);
request.setRequestHeader("Content-type","text/plain");
request.send(param);
// request.abort();
}
The input JSON-object is legit and the link-item is the predefined host IP of the server. The server-side code is Java-based and is the following:
public class Server {
public static void main(String args[]) throws Exception {
while (true) {
try {
ServerSocket ss = new ServerSocket(1024);
Socket s = ss.accept();
System.out.println("Request: ");
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter pw = new PrintWriter(s.getOutputStream());
String line;
while ((line = br.readLine()) != null) {
if (line.length() == 0) {
break;
}
System.out.print(line + "\r\n");
}
System.out.println("");
System.out.println("Response:");
String response = "HTTP/1.1 200 OK \r\n" + "Access-Control-Allow-Origin: * \r\n"
+ "Connection: close \r\n" + "\r\n";
System.out.println(response);
pw.write(response);
while ((line = br.readLine()) != null) {
if (line.length() == 0) {
break;
}
System.out.print(line + "\r\n");
}
br.close();
pw.close();
System.out.println("");
System.out.println("Socket Closed");
System.out.println("");
s.close();
ss.close();
} catch (Exception ex) {
// Do whatever
}
}
}}
The server does receive the request and the JSON-object, but no response is received on client side (readyState is usually 4, but status code is 0 and responseText is empty). Additionally the connection is not closed when I don't use request.abort() or close the extension's window. It for sure has nothing to do with the permissions in the manifest file, so I didn't include it in this post. Can somebody see what my mistake is or anybody have had a similar experience?
EDIT:
The HTTP request is received on server side and looks like:
POST / HTTP/1.1
Host: [IP address of the server; I deleted the exact address for privacy]
Connection: keep-alive
Content-Length: 173
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36
Origin: chrome-extension://nhpingbdjkkljheamibjobneeehiednk
Content-type: text/plain
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4,fr;q=0.2
Since the request is received on server side, I figured that the actual sending of the response is currently unsuccessful. Might it have something to do with the origin domain of the client? When I copy-paste that domain in my browser, I get a ERR_FILE_NOT_FOUND.
This is something that I feel should be very simple, but haven't been able to solve so far.
I'm working with a vendor system which has implemented a very basic API for our use. We send a GET request with an authentication token in the header, the server then returns us a PDF document in the body of the response.
All I want to do is display the PDF in the browser, any method would be fine, in a new tab or iframe etc.
I have managed to get this working in both firefox and chrome utilising the answer at: Request a file with a custom header But this does not work with IE 11, and IE11 is the only supported browser within our organisation.
Request headers are:
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Authorization:bearer ZYFXVEnE2Uf3kU0Ud8rFvq5pbV2IfrNzzJBAu8lI8p73reZ6-vdeChtXlGGN7NwUNvo2-5LKNd9FniZlcElplycBL4f2qu6EaHkO-Xb_-G5DR07p62UYq_DErl937Yc-mpLMphBBHC7-0uqYNfrivkbc3xeOvEBnRRtfagz7dYJ8EJive6QjwWjYgGj9HRQUAbcOggbJGxZDXmrlWTveUji-5CKb7w5guBUOhjyDkyB53r8rm2qptGfsp1NsKLU4h4kEDlNaxbbzB_oJQbuyIoG80BTnP-NB0bqOtPJ09FrM9AFVfrdJM0fRwS3BfxRgVNm01FgW-jQwp1GgzeAbS-3uRR1G92Y-rw6L8R17l31PPFlV_CNeK_oAG-AJldmn2lgv6a6l6Cj9s2OqOfXyX09iZIN6vIKXAqedSWb708GTNfJ7iLKjdGVYCYW1zZ9IZKXMyeMoK7nW_rDuMzmoXeLY3tGFeeOf27vuI4RdSaGVCD5kIynrYPe8fU1sp-KZE0i1aJ0qqQ9g7Nvg42ZsFIFHBqhRIY-k4Dxjm1jPloGNbFqhdc-GK5LYHcg_u3DwFbSUKWpXdzCPBn43qJ_yVfDqffQDsDafvGDKP0U4duq0eYNXYWKnB8VR7xytykWjXAj70a9SFPRocqhugiqJIwBMS6a5gfqlUssgEnCfhVGE_eGUSGrYdCvfHHKb-13O9m6dXomYFuK8Ql7H73MjDgzTihtYLULh3nAHrU-FehrBRsUeKpc32hKUVhVvTlw2lTOUcMhlC99EKPMT0hZhLy4t8e-icL2aqcKdN-S1rt-HU60cukw4SnLyM_Nfa-ytD8vtUwMLAV9K5h4DdK7H3LpfbQNbaHRfBjRk5aQ7Q2o
Content-type:application/json
Host: /vendor_URL/
Origin:null
Proxy-Connection:keep-alive
User-Agent:Mozilla/5.0 (Windows NT 6.3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36
Response Headers:
Accept-Ranges:none
Access-Control-Allow-Origin:*
Cache-Control:no-cache
Content-Disposition:inline; filename=GoToPlan.pdf
Content-Length:372483
Content-Type:application/pdf
Date:Wed, 26 Oct 2016 19:41:04 GMT
Expires:-1
Pragma:no-cache
Proxy-Connection:keep-alive
Server:Microsoft-IIS/7.5
Via:1.1 /proxy_URL/
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
Code that currently works in firefox and Chrome:
var document_http = new XMLHttpRequest();
var url = /document_URL/
document_http.open("GET", url, true);
//DOn'y know why, but needs this to display correctly
document_http.overrideMimeType( "application/octet-stream; charset=x-user-defined;" );
//Send the proper header information along with the request
document_http.setRequestHeader("Content-type", "application/json");
document_http.setRequestHeader("Authorization", "bearer " + auth_response[3]);
document_http.onreadystatechange = function() {//Call a function when the state changes.
if (document_http.readyState == 4 & document_http.status == 200) {
var data = toBinaryString(this.responseText);
data = "data:application/pdf;base64,"+btoa(data);
window.open(data);
}
}
document_http.send(params);
function toBinaryString(data) {
var ret = [];
var len = data.length;
var byte;
for (var i = 0; i < len; i++) {
byte=( data.charCodeAt(i) & 0xFF )>>> 0;
ret.push( String.fromCharCode(byte) );
}
return ret.join('');
}
Data URIs are subject to browsers' limitations on URLs. You can't reliably use them to display long content.
You can load the document as a blob, then use it in a iframe:
var xhr = new XMLHttpRequest();
xhr.open("GET", "/path/to/file.pdf");
xhr.responseType = "blob";
xhr.onload = function(res) {
iframe.src = URL.createObjectURL(res.response);
};
xhr.send();
This should work in every major browser. URL.createObjectURL will create a string of the form blob:http://host/unique-id that is a reference to the blob object.
Remember to call URL.revokeObjectURL on the given string when you're done showing the PDF. This will discard the reference to the blob, which can be safely garbage collected.
I send an octet-stream via ajax to my PHP server. I want to receive it as the octet stream and decode it, not as a string. The thing is that the request body is a string, and it seems that ajax sends it as plain text, even though I have overriden the mime type. This is my ajax:
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if(xmlhttp.status == 200){
console.log(xmlhttp);
}
else if(xmlhttp.status == 400) {
alert('There was an error 400')
}
else {
alert('something else other than 200 was returned')
}
}
};
xmlhttp.open("POST", "something.php", true);
xmlhttp.overrideMimeType("application/octet-stream");
xmlhttp.send(stream); // some array buffer
The request headers:
Request Method:POST
Status Code:200 OK
Remote Address:[::1]:80
Response Headers
view source
Connection:Keep-Alive
Content-Length:175
Content-Type:application/octet-stream
Date:Sat, 30 Apr 2016 17:07:04 GMT
Keep-Alive:timeout=5, max=99
Server:Apache/2.4.18 (Win32) OpenSSL/1.0.2e PHP/7.0.4
X-Powered-By:PHP/7.0.4
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4
Cache-Control:max-age=0
Connection:keep-alive
Content-Length:160
Request Payload
#9a54dbc4bdd16c1a19804751d113c44b#Some very boring string here :)
So the mime type is octet-stream, but the request payload is a string. What's wrong?
I have an ASP.NET WebAPI webservice that returns an object:
/// <summary>
/// upload a single file, as a new attachment, or overwrite an existing attachment
/// </summary>
/// <returns>new attachment, if created</returns>
[HttpPost, ActionName("uploadAttachment")]
public async Task<HttpResponseMessage> uploadAttachment(string jobid)
{
if (!Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
await Request.Content.ReadAsMultipartAsync(provider);
var attachment = [...];
return Request.CreateResponse(HttpStatusCode.OK, attachment);
}
... where "attachment" is a POCO object containing the information I need to return.
I'm calling it using XMLHttpRequest:
AttachmentService.prototype.uploadAttachment = function(jobid, name, imageData, notes, callback)
{
var url = [...];
var formData = new FormData();
formData.append('name', name);
formData.append('notes', notes);
formData.append('imageData', imageData);
var xhr = new XMLHttpRequest();
xhr.addEventListener('load', function(e)
{
var response = {};
if (e.target.status == 200)
{
response.success = true;
response.data = JSON.parse(e.target.response);
}
else
{
response.success = false;
response.message = e.target.message;
response.data = null;
}
callback(response);
});
xhr.open('POST', url, true);
//xhr.responseType = 'json';
xhr.setRequestHeader("authenticationToken", CORE.getAuthToken());
xhr.send(formData);
};
This works fine, in IE11 and Chrome. In Firefox 33, e.target.response is XML, not JSON.
I've done some browsing around the web, and have seen a number of suggestions, both client and server side. What seemed simplest was to specify the xhr.responseType, as in the comment in the code above.
And that doesn't work.
When I set "xhr.responseType = 'json'", e.target.response comes back null.
Ideas?
Additional info
Tried looking at the request headers in Fiddler.
In Chrome:
Accept: application/json, text/javascript, */*; q=0.01
In IE11:
Accept: */*
In Firefox:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
So that does seem to be the problem.
You can set the header to application/json
x.setRequestHeader('Content-type','application/json; charset=utf-8');
I'm developing an app in PhoneGap+dreamweaver cs5.5, who makes a call to a handler (.ashx) and returns a JSON string. I do the following:
function appReady(){
var ajax = new XMLHttpRequest();
ajax.open("GET","https://xxxx.xxxxx.com/xxxx/xxxx.ashx?method=GetUser&email=xxx#xxxx.com&pwd=123456",false);
ajax.send();
ajax.onreadystatechange=function(){
if(ajax.readyState == 4) {//Request complete !!
if (ajax.status == 200 || ajax.status == 0) { // OK response
alert(ajax.responseText);
document.getElementById('main').innerHTML = ajax.responseText;
}
}
}
}
When I running the app on the iphone emulator, I recover the json string responseText, but this comes empty on android emulator. In iphone the status returned is 200 but in android is 0.
if the problem was the coss-domain request, wouldn't work on any platform right?
I don't understand why the example of the wiki: http://wiki.phonegap.com/w/page/42450600/PhoneGap% 20Ajax% 20Sample
works correctly in two platforms and mine only in iphone ...
Check for cross-domain scripting issues. I did almost the same thing, except my URL was actually located on the same domain. It worked fine on Android and on a PC, but the iphone refused to function. When I changed from 'https://whatever.whatever.com/foo.asp' to just foo.asp - it worked!
var rootpath;
rootpath = "https://the.same.dam.place/foo.asp"; // did not work!
rootpath = "foo.asp"; // shortening it worked.
function read_foo(whatever)
{
var url = rootpath + "?whatever=" + whatever;
xmlHttp = GetXmlHttpObject(stateChanged);
xmlHttp.open("GET", url , true);
xmlHttp.send(null);
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
var return_place = document.getElementById('return_place');
var thetext = xmlHttp.responseText;
return_place.innerHTML= thetext;
}
}
also see:
Empty responseText from XMLHttpRequest