JSON Daten von einer Webseite erhalten

Jackcarver12

Mitglied
Hallo,
ich recherchiere jetzt schon mehrere Tage. Leider stoße ich immer wieder auf Sackgassen.
Ich habe eine Webseite geschrieben in der ein Nutzer via Checklisten Getränke bestellen kann.
Hat er alles angekreuzt und drückt auf bestellen, sammelt meine Java Script Funktion 2 Arrays und den Endbetrag.
Array1: Bestellung: Getränk1, Getränk2, Getränk3.....
Array2: PreisderGetränke: Preis1, Preis2, Preis3......

Daraus generiere ich ein JSON-Objekt via JavaScript.

1. Problem:
Wie kann ich über JavaScript diese JSON Datei einem Java Programm zugänglich machen?
2. Problem:
Wie kann ich das JSON im Java Programm entgegennehmen?

Was brauche ich dafür.
Hier ist mein bisheriger Code:

[CODE lang="html" title="HTML CODE"]<html>
<header>
<link href="standard.css" rel="stylesheet"/>
<script language="javascript" type="text/javascript" src="rechenscript.js"></script>


<title>
Cocktailseite
</title>

</header>
<body>
<!--
DropDown
-->

<nav>
<ul>
<li><a href="#" title="Nach Hause">Home</a></li>
<li class="submenu"><a href="#" title="nix">Regeln</a>
<ul>

<li><a href="#" title="Ihr Inventar">Spielregeln</a></li>
<li><a href="#" title="Unsere Auswahl">Verhaltensregeln</a></li>

</li>

</ul>
</li>
<li><a href="#" title="Ueber uns">Shop</a></li>
<li><a href="#" title="So erreichen Sie uns">Logout</a></li>

</ul>
</nav>
<div class:"Banner">
<img src="Banner.jpg" />
</div>
<h2>Unsere Cocktails </h2>

<form name="liste">
<ul class="Getraenkeliste">
<li class="auflistung">Cuba Libre<input type="checkbox" name="CubaLibre" id="getrank1" value="6.80" onclick="calcPrice()" class="getraenk"> </li>
<li class="auflistung">Sex on the Beach<input type="checkbox" name="SexOnTheBeach" id="getrank1" value="7.20" onclick="calcPrice()" class="getraenk"></li>
<li class="auflistung">Caipirinha<input type="checkbox" name="Caipirinha" id="getrank1" value="7.50" onclick="calcPrice()" class="getraenk"></li>
<li class="auflistung">Mochito<input type="checkbox" name="Mochito" id="getrank1" value="8.00" onclick="calcPrice()" class="getraenk"></li>
<li class="auflistung">Apple Teenie<input type="checkbox" name="AppleTeenie" id="getrank1" value="8.20" onclick="calcPrice()" class="getraenk"></li>
<li class="auflistung">Old Pesces<input type="checkbox" name="OldPesces" id="getrank1" value="9.00" onclick="calcPrice()" class="getraenk"></li>
<li class="auflistung">Tropic Thunder<input type="checkbox" name="TropicThunder" id="getrank1" value="8.40" onclick="calcPrice()" class="getraenk"></li>
</ul>
</form>
<div id="preisfeld">
<p>0.00</p>
</div>
<input type="submit" name="Bestellbutton" value="Bestellen" onclick="bestellung()">




</html>
[CODE lang="javascript" title="JavaScriptCode"]var summe=0.0;
var i;


function calcPrice()
{
var betrag=0.0;
var betragf=0.0;
var gecheckteBoxen=[];
var gecheckteBox;
var endsumme=0.0;


for(i=0;i<document.liste.length;i++)
{
if(document.liste.elements.checked)
{
/*rechnung*/
gecheckteBox = document.liste.elements.name;
String(gecheckteBox);
/*namen speichern*/
betrag = document.liste.elements.value;
/*betrag speichern*/
Number(betrag);
Number(summe);
summe=parseFloat(summe) + parseFloat(betrag);

}/*ende if*/
}/*ende for*/
/*Ausgabe*/
var element = document.getElementById("preisfeld");

if(summe===0)
{
element.innerHTML = "0.00"+"&#8364;";
}
else {
parseFloat(summe);
summe.toFixed(2);/* warum funktioniert das nicht*/
var summeS=String(summe);
/*Ausgabe */
element.innerHTML = String(summe)+ "0" + "&#8364;"; //0 wird angefügt, weil toFixed() nicht funktioniert

endsumme=summe;
summe=0;
betrag=0;
betragf=0;
}
return endsumme;
}



function bestellung()
{
var preisDerBox;
var preisDerBoxen=[];
var bestellung=[];
var endsumme=0.0;
var name;
var k=0;
let object;
var sendeObjekt;

endsumme=calcPrice();

for(i=0;i<document.liste.length;i++)
{
if(document.liste.elements.checked)
{
/*rechnung*/
gecheckteBox = document.liste.elements.name;
bestellung.push(gecheckteBox);
preisDerBox = document.liste.elements.value;
parseFloat(preisDerBox);
preisDerBoxen.push(preisDerBox);



bestellungJSON = {name: bestellung , preis: preisDerBoxen ,gesamtpreis: endsumme};

object = JSON.stringify(bestellungJSON);
sendeObjekt = JSON.parse(object);

// bestellungsListe.push({name: gecheckteBox, preis: preisDerBox})
//JSON erstellen
//let json = JSON.stringify(bestellung);
}/*ende if*/
}/*ende for*/


/* bestellung speichert alle namen */
/*endsumme speichert den Preis */
}
/* maybe....
function sendJSON()
{

var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function ()
{
if (xhr.readyState === 4 && xhr.status === 200)
{
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.password);
}
};
var data = JSON.stringify({"email": "hey@mail.com", "password": "101010"});
xhr.send(data);
}
}
*/


window.addEventListener("load", calcPrice());
[/CODE]

Mein JavaCode:
[CODE lang="java" title="Java Code"]package bk;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;

import org.json.JSONException;
import org.json.JSONObject;



import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;

//sendet einen Get Request an eine URL
public class Send_HTTP_Request2 {

public static void main(String[] args) {
try {
Send_HTTP_Request2.call_me();
} catch (Exception e) {
e.printStackTrace();
}
}

public static void call_me() throws Exception {
String url = "http://api.ipinfodb.com/v3/ip-city/?key=d64fcfdfacc213c7ddf4ef911dfe97b55e4696be3532bf8302876c09ebd06b&ip=74.125.45.100&format=json";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print in String
System.out.println(response.toString());
//Read JSON response and print
JSONObject myResponse = new JSONObject(response.toString());
System.out.println("result after Reading JSON Response");
System.out.println("statusCode- "+myResponse.getString("statusCode"));
System.out.println("statusMessage- "+myResponse.getString("statusMessage"));
System.out.println("ipAddress- "+myResponse.getString("ipAddress"));
System.out.println("countryCode- "+myResponse.getString("countryCode"));
System.out.println("countryName- "+myResponse.getString("countryName"));
System.out.println("regionName- "+myResponse.getString("regionName"));
System.out.println("cityName- "+myResponse.getString("cityName"));
System.out.println("zipCode- "+myResponse.getString("zipCode"));
System.out.println("latitude- "+myResponse.getString("latitude"));
System.out.println("longitude- "+myResponse.getString("longitude"));
System.out.println("timeZone- "+myResponse.getString("timeZone"));
}
}
/*
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}

public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}

public static void main(String[] args) throws IOException, JSONException {
JSONObject json = readJsonFromUrl("https://swapi.co/api/people/1/");
System.out.println(json.toString());
System.out.println(json.get("id"));
}
*/

[/CODE]

Mittlerweile bin ich mir nicht mehr sicher ob ich den benutzten Code richtig verstehe. Das ist das was ich bisher recherchiert habe. Ich finde allerdings zu dem besagten Fall keine ordentliche Lösung.
Kann mir jemand helfen?
LG J
 
Ok ich habe jetzt etwas weiter recherchiert und erkannt, dass mein Ansatz so nicht funktioniert.
Meine Idee war nun einen HTTPServer über Java zu erzeugen.
Ich habe mir dazu folgenden Code aus GitHub geholt.

[CODE lang="java" title="JavaCode HTTP Server"]package bkServer;


import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.i😵utputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.StringTokenizer;

// The tutorial can be found just here on the SSaurel's Blog :
// https://www.ssaurel.com/blog/create-a-simple-http-web-server-in-java
// Each Client Connection will be managed in a dedicated Thread
public class JavaHTTPServer implements Runnable
{

static final File WEB_ROOT = new File(".");
static final String DEFAULT_FILE = "index.html";
static final String FILE_NOT_FOUND = "404.html";
static final String METHOD_NOT_SUPPORTED = "not_supported.html";
// port to listen connection
static final int PORT = 8080;

// verbose mode
static final boolean verbose = true;

// Client Connection via Socket Class
private Socket connect;

public JavaHTTPServer(Socket c) {
connect = c;
}

public static void main(String[] args) {
try {
ServerSocket serverConnect = new ServerSocket(PORT);
System.out.println("Server started.\nListening for connections on port : " + PORT + " ...\n");

// we listen until user halts server execution
while (true) {
JavaHTTPServer myServer = new JavaHTTPServer(serverConnect.accept());

if (verbose) {
System.out.println("Connecton opened. (" + new Date() + ")");
}

// create dedicated thread to manage the client connection
Thread thread = new Thread(myServer);
thread.start();
}

} catch (IOException e) {
System.err.println("Server Connection error : " + e.getMessage());
}
}

@Override
public void run() {
// we manage our particular client connection
BufferedReader in = null; PrintWriter out = null; BufferedOutputStream dataOut = null;
String fileRequested = null;

try {
// we read characters from the client via input stream on the socket
in = new BufferedReader(new InputStreamReader(connect.getInputStream()));
// we get character output stream to client (for headers)
out = new PrintWriter(connect.getOutputStream());
// get binary output stream to client (for requested data)
dataOut = new BufferedOutputStream(connect.getOutputStream());

// get first line of the request from the client
String input = in.readLine();
// we parse the request with a string tokenizer
StringTokenizer parse = new StringTokenizer(input);
String method = parse.nextToken().toUpperCase(); // we get the HTTP method of the client
// we get file requested
fileRequested = parse.nextToken().toLowerCase();

// we support only GET and HEAD methods, we check
if (!method.equals("GET") && !method.equals("HEAD")) {
if (verbose) {
System.out.println("501 Not Implemented : " + method + " method.");
}

// we return the not supported file to the client
File file = new File(WEB_ROOT, METHOD_NOT_SUPPORTED);
int fileLength = (int) file.length();
String contentMimeType = "text/html";
//read content to return to client
byte[] fileData = readFileData(file, fileLength);

// we send HTTP Headers with data to client
out.println("HTTP/1.1 501 Not Implemented");
out.println("Server: Java HTTP Server from SSaurel : 1.0");
out.println("Date: " + new Date());
out.println("Content-type: " + contentMimeType);
out.println("Content-length: " + fileLength);
out.println(); // blank line between headers and content, very important !
out.flush(); // flush character output stream buffer
// file
dataOut.write(fileData, 0, fileLength);
dataOut.flush();

} else {
// GET or HEAD method
if (fileRequested.endsWith("/")) {
fileRequested += DEFAULT_FILE;
}

File file = new File(WEB_ROOT, fileRequested);
int fileLength = (int) file.length();
String content = getContentType(fileRequested);

if (method.equals("GET")) { // GET method so we return content
byte[] fileData = readFileData(file, fileLength);

// send HTTP Headers
out.println("HTTP/1.1 200 OK");
out.println("Server: Java HTTP Server from SSaurel : 1.0");
out.println("Date: " + new Date());
out.println("Content-type: " + content);
out.println("Content-length: " + fileLength);
out.println(); // blank line between headers and content, very important !
out.flush(); // flush character output stream buffer

dataOut.write(fileData, 0, fileLength);
dataOut.flush();
}

if (verbose) {
System.out.println("File " + fileRequested + " of type " + content + " returned");
}

}

} catch (FileNotFoundException fnfe) {
try {
fileNotFound(out, dataOut, fileRequested);
} catch (IOException ioe) {
System.err.println("Error with file not found exception : " + ioe.getMessage());
}

} catch (IOException ioe) {
System.err.println("Server error : " + ioe);
} finally {
try {
in.close();
out.close();
dataOut.close();
connect.close(); // we close socket connection
} catch (Exception e) {
System.err.println("Error closing stream : " + e.getMessage());
}

if (verbose) {
System.out.println("Connection closed.\n");
}
}


}

private byte[] readFileData(File file, int fileLength) throws IOException {
FileInputStream fileIn = null;
byte[] fileData = new byte[fileLength];

try {
fileIn = new FileInputStream(file);
fileIn.read(fileData);
} finally {
if (fileIn != null)
fileIn.close();
}

return fileData;
}

// return supported MIME Types
private String getContentType(String fileRequested) {
if (fileRequested.endsWith(".htm") || fileRequested.endsWith(".html"))
return "text/html";
else
return "text/plain";
}

private void fileNotFound(PrintWriter out, OutputStream dataOut, String fileRequested) throws IOException {
File file = new File(WEB_ROOT, FILE_NOT_FOUND);
int fileLength = (int) file.length();
String content = "text/html";
byte[] fileData = readFileData(file, fileLength);

out.println("HTTP/1.1 404 File Not Found");
out.println("Server: Java HTTP Server from SSaurel : 1.0");
out.println("Date: " + new Date());
out.println("Content-type: " + content);
out.println("Content-length: " + fileLength);
out.println(); // blank line between headers and content, very important !
out.flush(); // flush character output stream buffer

dataOut.write(fileData, 0, fileLength);
dataOut.flush();

if (verbose) {
System.out.println("File " + fileRequested + " not found");
}
}

}



[/CODE]

Mein Ziel wäre also:
JavaScript erstellt JSON -> JSON über Post an Java -> Java verarbeitet JSON und erzeugt ein Objekt welches verarbeitet werden kann.

Hoffe jemand erbarmt sich.
LG J
 
Wie du schon richtig sagst brauchst du einen Http-Server, aber anstatt den selber zu programmieren solltest du irgendein Framework nutzen, und darauf aufbauen 🙂

Spring Boot oder Quarkus dürften das einfachste sein, Möglichkeiten gibts aber wie Sand am mehr.
 

Zurück
Oben