Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k views
in Technique[技术] by (71.8m points)

How do I send a java object in a HTTP Request?

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Firstly you have to make your Place class serializable, by

implementing java.io.Serializable

Then the Place object needs to be converted to a json object, which can be done easily by using Jackson or GSON libraries.

Example using Gson:

Gson gson = new Gson();
String json = gson.toJson(placeObject);

Later while receiving the response you can deserialize it back to Place object using the same library.

Place placeObject = new Gson().fromJson(json, Place.class);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...