I am making a text game where it is necessary to upload a Object (Place) to a Java web server. (Players need to share data, however security is not a concern here) I am using the java.net.http APIs. My current method is
public void sendNewPlace(Place place) {
HttpRequest.BodyPublisher publisher =
HttpRequest.BodyPublishers.ofInputStream(() -> {
PipedInputStream in = new PipedInputStream();
ForkJoinPool.commonPool().submit(() -> {
try (PipedOutputStream out = new PipedOutputStream(in)) {
return place;
}
});
return in;
});
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://127.0.0.1:410/Places/Send/"))
.POST(publisher)
.build();
try {
client.send(request, HttpResponse.BodyHandlers.discarding());
} catch (IOException | InterruptedException e) {
System.out.println("Error: " + e + ", please contact game admin.");
}
}
But this throws java.io.IOException: chunked transfer encoding, state: READING_LENGTH
on client.send()
. I really have no clue what I should do to fix this, all the tutorials and StackOverflow questions either use a 3rd-party API, outdated code (pre-java 9), or want to send a String or JSON. Which are all very unhelpful. I am not super sure what this code does, I found it on a tutorial or question and modified it. I am sure I do not want to try to use JSON, and I definitely do not want to use ANY 3rd-party libraries. In case you were wondering, my server code is as follows:
public void makePlacesRecieveContext() {
server.createContext("/Places/Send/", new HttpHandler() {
public void handle(HttpExchange exchange) throws IOException {
System.out.println("Hit! /Places/Send/");
exchange.sendResponseHeaders(200, 0);
ObjectInputStream out = new ObjectInputStream(exchange.getRequestBody());
try {
Place pl = (Place)out.readObject();
GetResponces.writeFile(new File("C://Users//programmerGuy//gameServer//Places//" + pl.getName()),pl);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
out.close();
exchange.getRequestBody().close();
System.out.println(exchange.getRemoteAddress().getHostName() + " : " + exchange.getRemoteAddress().getHostString());
}
});
}
GetResponces is a class I built to handle most File IO. All I need to do is be able to upload these Place objects to the server, my question is, how do I do that?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…