Sending binary data to server - javascript

I create an array buffer containing some data:
var myArray = new ArrayBuffer(512);
var longInt8View = new Uint8Array(myArray);
for (var i = 0; i < longInt8View.length; i++) {
longInt8View[i] = i % 255;
}
And I send it so a server via POST:
if (window.XMLHttpRequest) {
var xmlhttp = new XMLHttpRequest();
} else {
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
action(xmlhttp.responseText);
}
};
xmlhttp.open("POST", 'http://somedomain.com:8080', true);
xmlhttp.send(myArray);
var action = function (response) {
console.log(response);
};
I now want to receive these binary data in go code, and do something with it. How can I do this?
package main
import (
"fmt"
"net/http"
)
func handleRequest(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "*")
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintf(w, "%s", r.Body)
}
func main() {
http.HandleFunc("/", handleRequest)
http.ListenAndServe(":8080", nil)
}
I can see a reference to a memory block inside the body, but how do I get this specificaly?

Don't send binary data over HTTP protocol. Convert them in Base64. Send them as a normal string. Decode them from Base64 to binary on the server side.
To convert a binary data to base64 you can use the function btoa

Related

Trying to post to a .txt file fails but performing a get does work

My partner and I are trying to get a domain that I own, communicate with a ios app that is run on objective c to work via http. He is using the code that was provided by this link Sending an HTTP POST request on iOS.
He is able to do a GET to receive the data in my .txt page but when he performs a PUT to try and write to that file so that I can get that data it fails. We are both rather new to http so it is possible that we are missing something. A concern we have is that he doesn't have the privileges to write to this file. Any advice would help, thanks!
Here is the javascript I am using on my side. I added a header to my response to try and resolve the cors issue.
(function () {
window.onload = function () {
httpGetAsync("http://students.washington.edu/bharatis/distances.txt", processData)
//alert("hello inside onload");
document.getElementById("first").innerHTML = leader1;
document.getElementById("second").innerHTML = leader1;
document.getElementById("third").innerHTML = leader1;
//window.onbeforeunload = update;
}
function processData(responseText) {
//alert(responseText);
var txt = "";
var x = responseText.getElementsByTagName('Distance'); // Talk to alex about
for(i = 0; i < x.length; i++) {
txt += x[i].childNodes[0].nodeValue;
}
var result = parseDouble(txt);
alert(result);
}
function httpGetAsync(theUrl, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xmlHttp.send("response message");
}
})();

How can I pass a parameter from javascript to RESTful web service using XMLHttpRequest

When i try to print the received parameter at the web service.
The parameter is empty.
If I view domain server log of glass fish server I can see the following
print:
Inside getJson()
countryKey =
So I understand the request arruved to the web service, but the parameter
that was sent from the javascript url is empty
// This is the code of the web service method
#GET
#Produces(MediaType.APPLICATION_JSON)
public String getJson(String countryKey) {
System.out.println("Inside getJson()");
System.out.println("countryKey = " + countryKey);
return "countryKey = " + countryKey;
}
// This is the javascript method
function populateDistrictList() {
var element = document.getElementById("selectCountry");
var selectedCountryKey = element.value;
var selectedCountry = element.options[element.selectedIndex].text;
var xmlHttp = new XMLHttpRequest();
var url = "http://localhost:8080/MissionWS/webresources/generic?selectedCountryKey="+selectedCountryKey;
xmlHttp.open('GET', url, true);
xmlHttp.responseType = 'json';
if (xmlHttp) {
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
alert(xmlHttp.responseText);
} else {
alert("Something is wrong !");
}
}
};
xmlHttp.send();
}
}
Please try adding the #QueryParam to your method signature as follows.
public String getJson(#QueryParam("selectedCountryKey") String countryKey)

Login using Javascript and REST

I made a REST service, which will return a String "hej" if the log in is true.
I have tested in Java with a rest client and it works fine, but pretty new to javascript and need some help.
I'm using this function
function UserAction() {
console.log(User());
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "http://localhost:8080/Footballmanagerrestservice/webresources/login");
xhttp.setRequestHeader("login", User());
xhttp.responseType = 'text';
xhttp.onreadystatechange = function () {
console.log('DONE', xhttp.readyState);
if (xhttp.readyState == 4) {;
// handle response
var response = xhttp.responseText;
console.log(response);
if (response == "hej") {
var url = "http://localhost:8080/FM3/spil2.jsp";
window.location.href = url;
}
}
};
// send the request *after* the callback is defined
xhttp.send();
return false;
}
function User() {
username = document.getElementById("username").toString();
username = document.getElementById("password").toString();
var UserAndPass = "?username=" + username + "&password=" + password;
return UserAndPass;
}
I show you the client i have i Java, maybe you can see why it's not working.
public static void main(String[] args) {
Client client = ClientBuilder.newClient();
String root="http://localhost:8080/Footballmanagerrestservice/webresources/";
String functionPath="login";
String parameters="?username=s153518&password=holger";
Response res = client.target(root+functionPath+parameters)
.request(MediaType.APPLICATION_JSON).get();
String svar = res.readEntity(String.class);
System.out.println(svar);
}
first part of the code looks ok, the following instead must be handled inside a function because is intrinsically asynchronous
var response = JSON.parse(xhttp.responseText);
console.log(response);
if (response.toString() == "hej") {
var url = "http://localhost:8080/FM3/spil2.jsp";
window.location.href = url
}
return false;
doc: https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/onreadystatechange
essentially you're trying to handle the response as a syncrhonous call, but it's not, the response it's not immediatly avaiable, for this reason you have to register a callback (from the doc must be attached to the field onreadystatechange) that will be triggered by javascript as soon as the server response is available.
try to change it like so:
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4) {
// handle response
var response = JSON.parse(xhttp.responseText);
console.log(response);
if (response.toString() == "hej") {
var url = "http://localhost:8080/FM3/spil2.jsp";
window.location.href = url
}
}
}
xhr.send();

Create an HTTP request after btoa() is complete in javascript

I am trying to send a file as a base64 string to a server. The server requires that the data is sent as an HTTP 'POST' with the information is JSON. However, in my code, the request is sent before the string is converted. Please advise on what error I am making in my code.
This is the function which converts the file
function handleFileSelect(evt) {
var files = evt.files;
var file = files[0];
var string = '';
if (files && file)
{
var reader = new FileReader();
reader.onload = function(readerEvt)
{
var binaryString = readerEvt.target.result;
string = btoa(binaryString);
};
reader.readAsBinaryString(file);
}
create_HTTP_request(string);};
This is my HTTP request function(s)
function create_HTTP_request(string)
{
runTask('task_required_by_server', {'file' : string}, format_data);
};
function runTask(task_name, inputs, callback){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log('Request Successful!');
callback(xmlhttp.responseText);
console.log(xmlhttp.responseText);
}
else if(xmlhttp.readyState == 4 && xmlhttp.status == 500)
{
console.log(xmlhttp.responseText);
}
else {
console.log(xmlhttp.responseText);
}
}
xmlhttp.open("POST", '/api/v1/jobs', true);
xmlhttp.setRequestHeader('Content-Type', 'application/json');
xmlhttp.send(JSON.stringify({name: task_name, input: inputs}));
};
I am new to Javascript. I basically want to call my create_HTTP_request function only after the btoa() function is complete. Thanks for your time!

Adding headers to c# HTTP server

I'm trying to make a HTTP server (listener) in c# using the "Simple HTTP server in c#" - (http://www.codeproject.com/Articles/137979/Simple-HTTP-Server-in-C), and send requests to it using javascript.
This is what the code looks like:
The HandleRequest function in c#:
public override void handleGETRequest(HttpProcessor p)
{
p.httpHeaders.Add("Access-Control-Allow-Origin", "*");
if (p.http_url.Equals("/test"))
{
p.outputStream.Write("Test accomplished");
Console.Log("Server responded to TEST request successfully");
return;
}
if (p.http_url.StartsWith("/goto"))
{
string[] args = p.http_url.Split('/');
//x - [2]
//y - [3]
//z - [4]
//f - [5]
myPrinter.SendCommand(string.Format("G1X{0}Y{1}F10000", args[2], args[3]));
p.outputStream.Write("response succeeded");
Console.Log("goto command was executed");
}
if (p.http_url.StartsWith("/commandlist"))
{
string[] args = p.http_url.Split('/');
//[2] - commands
string[] commands = args[2].Split('$');
for (int i = 0; i < commands.Length; i++)
{
myPrinter.commands.Add(commands[i]);
}
//myPrinter.HandleCommandList();
p.outputStream.Write("response succeeded");
Console.Log("goto command was executed");
}
if (p.http_url.StartsWith("/execute"))
{
p.outputStream.Write("Executing " + myPrinter.commands.Count + " commands\n");
myPrinter.HandleCommandList();
}
}
The request sending in JS look like that:
function sendGCODE() {
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:1300/commandlist/" + document.getElementById("Text1").value;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = xmlhttp.responseText;
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
alert('Response received');
document.getElementById("resultP").innerHTML = arr;
}
}
But when I try sending the request from the JS code, it just tells me that "Access-Control-Allow-Origin" header is missing, and so it can't send the request. I added that header in the beginning of the handleGETRequest() function like that:
public override void handleGETRequest(HttpProcessor p)
{
p.httpHeaders.Add("Access-Control-Allow-Origin", "*");
So why doesn't it work? The serverside software doesn't throw an error, but the JS code is still upset because of the missing header.
What am I doing wrong? Thanks! (the rest of the server side code is in the link above)
I think you should enable CORS for your server to accept those requests, take a look at this guide , maybe it will help.

Categories

Resources