java.net.http.httpclient不发布对服务器的数据?

发布于 2025-02-03 14:27:28 字数 3722 浏览 1 评论 0原文

我正在尝试写一个简单的HTTP客户端&使用新的(JDK 11)httpclient的服务器。

JDK。:OpenJDK 17.0.0

客户端正在连接到服务器,但似乎并未发布任何数据。

服务器接收到传入连接后,它尝试读取数据。
读取永无止境。
有人知道我在做什么错吗?

服务器来源:

package de.ipp.client.server;

import java.io.*;
import java.net.*;
import java.time.ZonedDateTime;

public class IppServer {

    public static final int PORT = 31613;

    public static void main(String[] args) throws IOException {

        System    .out.println(ZonedDateTime.now() + " IppServer Start.....");

        try(final ServerSocket serverSocket = new ServerSocket(PORT))
        {
            System.out.println(ZonedDateTime.now() + " IppServer Running..: " + serverSocket);

            while (true) {
                final Thread thread = new Thread(getSocketRunnable(serverSocket.accept()));
                ;            thread.setDaemon(true);
                ;            thread.start();
            }
        }
    }

    private static Runnable getSocketRunnable(final Socket socket) {
        return () -> {
            System    .out.println(ZonedDateTime.now() + " IppServer Socket...: incoming -> " + socket);

            try(final InputStream ist   = socket.getInputStream())
            {
                System.out.println(ZonedDateTime.now() + " IppServer Reading...");

                final byte[]      bytes = ist.readAllBytes();

                System.out.println(ZonedDateTime.now() + " IppServer L'Bytes..: " + bytes.length);
            }
            catch (final IOException e) {
                System.out.println(ZonedDateTime.now() + " IppServer Error!!..: " + e.getMessage());
            }
        };
    }
}

客户来源:

package de.ipp.client.server;

import java.net.URI;
import java.net.http.*;
import java.net.http.HttpClient.Version;
import java.net.http.HttpRequest.*;
import java.net.http.HttpResponse.BodyHandlers;
import java.time.ZonedDateTime;

public class IppClient {

    public static void main(final String[] args) throws Exception {

        final URI                  uri       = new URI("http://localhost:" + IppServer.PORT + "/printers");
        final BodyPublisher        publisher = HttpRequest.BodyPublishers.ofByteArray("SomeBytes".getBytes());

        final Builder              builder   = HttpRequest.newBuilder();
        ;                          builder.uri      (uri);
        ;                          builder.version  (Version.HTTP_1_1);
        ;                          builder.setHeader("Transfer-Encoding", "chunked");
        ;                          builder.setHeader("Content-Type",      "application/ipp");
        ;                          builder.setHeader("Accept-Encoding",   "gzip,deflate");
        ;                          builder.POST(publisher);

        final HttpRequest          request   = builder.build();

        System.out.println(ZonedDateTime.now() + " IppClient Posting..: " + uri);

        final HttpResponse<byte[]> response  = HttpClient.newHttpClient().send(request, BodyHandlers.ofByteArray());

        System.out.println(ZonedDateTime.now() + " IppClient Response.: " + response.statusCode());
    }
}

日志:

2022-06-02T11:52:23.378674200+02:00[Europe/Berlin] IppServer Start.....
2022-06-02T11:52:23.411587200+02:00[Europe/Berlin] IppServer Running..: ServerSocket[addr=0.0.0.0/0.0.0.0,localport=31613]
2022-06-02T11:53:31.229082300+02:00[Europe/Berlin] IppServer Socket...: incoming -> Socket[addr=/127.0.0.1,port=55978,localport=31613]
2022-06-02T11:53:31.232074700+02:00[Europe/Berlin] IppServer Reading...

2022-06-02T11:53:30.474583800+02:00[Europe/Berlin] IppClient Posting..: http://localhost:31613/printers

I'm trying to write a simple HTTP Client & Server using the new (JDK 11) HttpClient.

JDK.: OpenJDK 17.0.0

The Client is connecting to the Server but doesn't seem to be POST'ing any data.

After the Server receives the incoming Connection, it tries to read the data.
The read never ends.
Does anyone know what I'm doing wrong?

Server Source:

package de.ipp.client.server;

import java.io.*;
import java.net.*;
import java.time.ZonedDateTime;

public class IppServer {

    public static final int PORT = 31613;

    public static void main(String[] args) throws IOException {

        System    .out.println(ZonedDateTime.now() + " IppServer Start.....");

        try(final ServerSocket serverSocket = new ServerSocket(PORT))
        {
            System.out.println(ZonedDateTime.now() + " IppServer Running..: " + serverSocket);

            while (true) {
                final Thread thread = new Thread(getSocketRunnable(serverSocket.accept()));
                ;            thread.setDaemon(true);
                ;            thread.start();
            }
        }
    }

    private static Runnable getSocketRunnable(final Socket socket) {
        return () -> {
            System    .out.println(ZonedDateTime.now() + " IppServer Socket...: incoming -> " + socket);

            try(final InputStream ist   = socket.getInputStream())
            {
                System.out.println(ZonedDateTime.now() + " IppServer Reading...");

                final byte[]      bytes = ist.readAllBytes();

                System.out.println(ZonedDateTime.now() + " IppServer L'Bytes..: " + bytes.length);
            }
            catch (final IOException e) {
                System.out.println(ZonedDateTime.now() + " IppServer Error!!..: " + e.getMessage());
            }
        };
    }
}

Client Source:

package de.ipp.client.server;

import java.net.URI;
import java.net.http.*;
import java.net.http.HttpClient.Version;
import java.net.http.HttpRequest.*;
import java.net.http.HttpResponse.BodyHandlers;
import java.time.ZonedDateTime;

public class IppClient {

    public static void main(final String[] args) throws Exception {

        final URI                  uri       = new URI("http://localhost:" + IppServer.PORT + "/printers");
        final BodyPublisher        publisher = HttpRequest.BodyPublishers.ofByteArray("SomeBytes".getBytes());

        final Builder              builder   = HttpRequest.newBuilder();
        ;                          builder.uri      (uri);
        ;                          builder.version  (Version.HTTP_1_1);
        ;                          builder.setHeader("Transfer-Encoding", "chunked");
        ;                          builder.setHeader("Content-Type",      "application/ipp");
        ;                          builder.setHeader("Accept-Encoding",   "gzip,deflate");
        ;                          builder.POST(publisher);

        final HttpRequest          request   = builder.build();

        System.out.println(ZonedDateTime.now() + " IppClient Posting..: " + uri);

        final HttpResponse<byte[]> response  = HttpClient.newHttpClient().send(request, BodyHandlers.ofByteArray());

        System.out.println(ZonedDateTime.now() + " IppClient Response.: " + response.statusCode());
    }
}

Logs:

2022-06-02T11:52:23.378674200+02:00[Europe/Berlin] IppServer Start.....
2022-06-02T11:52:23.411587200+02:00[Europe/Berlin] IppServer Running..: ServerSocket[addr=0.0.0.0/0.0.0.0,localport=31613]
2022-06-02T11:53:31.229082300+02:00[Europe/Berlin] IppServer Socket...: incoming -> Socket[addr=/127.0.0.1,port=55978,localport=31613]
2022-06-02T11:53:31.232074700+02:00[Europe/Berlin] IppServer Reading...

2022-06-02T11:53:30.474583800+02:00[Europe/Berlin] IppClient Posting..: http://localhost:31613/printers

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

家住魔仙堡 2025-02-10 14:27:28

再次感谢 @dave_thompson_085对ReadAllBytes的评论。

这是一个很好的帮助。

这不是写一个HTTP服务器的目的,只需找到Cups4J在线路上发送的内容&amp;基于新的(JDK 11)httpclient编写客户端以替换它。

这是我修改的资源&amp;一些日志记录输出...

客户端来源:

package de.ipp.client.server;

import java.net.URI;
import java.net.http.*;
import java.net.http.HttpRequest.*;
import java.net.http.HttpResponse.BodyHandlers;
import java.time.Duration;

public class IppClient {

    public static final byte[] PAYLOAD = "SomeBytes".getBytes();

    public static void main(final String[] args) throws Exception {
        Thread.currentThread().setName("myClient");

        final URI         uri     = new URI("http://localhost:" + IppServer.PORT + "/printers");

        final Builder     builder = HttpRequest.newBuilder();
        ;                 builder.uri      (uri);
        ;                 builder.setHeader("Content-Type", "application/ipp");
        ;                 builder.POST     (HttpRequest.BodyPublishers.ofByteArray(PAYLOAD));

        System.out.println(IppServer.logPrefix() + "IppClient Posting.: " + uri);

        HttpClient.newBuilder().build().sendAsync(builder.build(), BodyHandlers.ofByteArray());

        Thread.sleep(Duration.ofSeconds(3).toMillis()); // (give Server time to serve!!)

        System.out.println(IppServer.logPrefix() + "IppClient Posted... (async)");
    }
}

服务器来源:

package de.ipp.client.server;

import java.io.*;
import java.net.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;

public class IppServer {

    private static final DateTimeFormatter HH_MM_SS_NANOS = DateTimeFormatter.ofPattern("HH.mm.ss.SSSSSSSSS' '");

    public  static final int PORT = 31613;

    public  static void main(final String[] args) throws IOException {
        Thread.currentThread().setName("LISTENER");

        System        .out.println(logPrefix() + "IppServer Start....");

        try(final ServerSocket serverSocket = new ServerSocket(PORT))
        {
            System    .out.println(logPrefix() + "IppServer Running.: " + serverSocket);

            while (true) {
                final Socket socket = serverSocket.accept();

                System.out.println(logPrefix() + "IppServer Socket..: incoming -> " + socket);

                final Thread thread = new Thread(getSocketRunnable(socket));
                ;            thread.setDaemon(true);
                ;            thread.start();
            }
        }
    }

    private static Runnable getSocketRunnable(final Socket socket) {
        return () -> {
            try(final InputStream ist   = socket.getInputStream())
            {
                System.out.println(logPrefix() + "IppServer Reading..");

                final byte[]      buf   = new byte[4096];
                ;     int         count;

                while ((count = ist.read(buf)) != -1) {
                    logBytes(buf, count);

                    if (0 == Arrays.compare(buf, 0, count, IppClient.PAYLOAD, 0, IppClient.PAYLOAD.length)) {
                        /*
                         * For our purposes, it is sufficient that the payload was received OK.
                         * We do not need to complete the HTTP Handshake, so just break off the dialogue...
                         */
                        break;
                    }
                }
            }
            catch (final IOException e) {
                System.out.println(logPrefix() + "IppServer Error!!.: " + e.getMessage());
            }
        };
    }

    private static void logBytes(final byte[] bytes, final int count) {

        final StringBuilder sbd = new StringBuilder(count * 2);
        ;     byte          b;

        for (int i=0; i < count; i++) {
            b = bytes[i];

            if (b > 32   ) {sbd.append( (char) b);  continue;}

            if (b == '\r') {sbd.append("[\\r]");    continue;}
            if (b == '\n') {sbd.append("[\\n]");    continue;}

            sbd.append("[0x").append(Integer.toHexString(b)).append(']');
        }
        System.out.println(logPrefix() + "IppServer Bytes...: L=" + count + '\t' + sbd.toString());
    }

    public static String logPrefix() {
        return '[' + Thread.currentThread().getName() + "] " + HH_MM_SS_NANOS.format(LocalDateTime.now());
    }
}

日志:

[LISTENER] 08.49.25.232446900 IppServer Start....
[LISTENER] 08.49.25.261367100 IppServer Running.: ServerSocket[addr=0.0.0.0/0.0.0.0,localport=31613]
[LISTENER] 08.49.38.749640100 IppServer Socket..: incoming -> Socket[addr=/127.0.0.1,port=65073,localport=31613]
[Thread-0] 08.49.38.753629400 IppServer Reading..
[Thread-0] 08.49.38.776568000 IppServer Bytes...: L=246 POST[0x20]/printers[0x20]HTTP/1.1[\r][\n]Connection:[0x20]Upgrade,[0x20]HTTP2-Settings[\r][\n]Content-Length:[0x20]9[\r][\n]Host:[0x20]localhost:31613[\r][\n]HTTP2-Settings:[0x20]AAEAAEAAAAIAAAABAAMAAABkAAQBAAAAAAUAAEAA[\r][\n]Upgrade:[0x20]h2c[\r][\n]User-Agent:[0x20]Java-http-client/17.0.1[\r][\n]Content-Type:[0x20]application/ipp[\r][\n][\r][\n]
[Thread-0] 08.49.38.780556300 IppServer Bytes...: L=9   SomeBytes
[LISTENER] 08.50.22.853368800 IppServer Socket..: incoming -> Socket[addr=/127.0.0.1,port=65091,localport=31613]
[Thread-1] 08.50.22.854365100 IppServer Reading..
[Thread-1] 08.50.22.880294200 IppServer Bytes...: L=246 POST[0x20]/printers[0x20]HTTP/1.1[\r][\n]Connection:[0x20]Upgrade,[0x20]HTTP2-Settings[\r][\n]Content-Length:[0x20]9[\r][\n]Host:[0x20]localhost:31613[\r][\n]HTTP2-Settings:[0x20]AAEAAEAAAAIAAAABAAMAAABkAAQBAAAAAAUAAEAA[\r][\n]Upgrade:[0x20]h2c[\r][\n]User-Agent:[0x20]Java-http-client/17.0.1[\r][\n]Content-Type:[0x20]application/ipp[\r][\n][\r][\n]
[Thread-1] 08.50.22.885280900 IppServer Bytes...: L=9   SomeBytes
[LISTENER] 09.01.07.880173600 IppServer Socket..: incoming -> Socket[addr=/127.0.0.1,port=65397,localport=31613]
[Thread-2] 09.01.07.881169400 IppServer Reading..
[Thread-2] 09.01.07.908097800 IppServer Bytes...: L=246 POST[0x20]/printers[0x20]HTTP/1.1[\r][\n]Connection:[0x20]Upgrade,[0x20]HTTP2-Settings[\r][\n]Content-Length:[0x20]9[\r][\n]Host:[0x20]localhost:31613[\r][\n]HTTP2-Settings:[0x20]AAEAAEAAAAIAAAABAAMAAABkAAQBAAAAAAUAAEAA[\r][\n]Upgrade:[0x20]h2c[\r][\n]User-Agent:[0x20]Java-http-client/17.0.1[\r][\n]Content-Type:[0x20]application/ipp[\r][\n][\r][\n]
[Thread-2] 09.01.07.914083500 IppServer Bytes...: L=9   SomeBytes

[myClient] 09.01.06.956313800 IppClient Posting.: http://localhost:31613/printers
[myClient] 09.01.10.783634700 IppClient Posted... (async)

Once again, many thanks to @dave_thompson_085 for the comments regarding readAllBytes.

That was a great help.

It was not the intention to write an HTTP-Server, just find exactly what CUPS4J was sending over the line & write a Client based on the new (JDK 11) HttpClient to replace it.

Here are my modified sources & some logging output...

Client Source:

package de.ipp.client.server;

import java.net.URI;
import java.net.http.*;
import java.net.http.HttpRequest.*;
import java.net.http.HttpResponse.BodyHandlers;
import java.time.Duration;

public class IppClient {

    public static final byte[] PAYLOAD = "SomeBytes".getBytes();

    public static void main(final String[] args) throws Exception {
        Thread.currentThread().setName("myClient");

        final URI         uri     = new URI("http://localhost:" + IppServer.PORT + "/printers");

        final Builder     builder = HttpRequest.newBuilder();
        ;                 builder.uri      (uri);
        ;                 builder.setHeader("Content-Type", "application/ipp");
        ;                 builder.POST     (HttpRequest.BodyPublishers.ofByteArray(PAYLOAD));

        System.out.println(IppServer.logPrefix() + "IppClient Posting.: " + uri);

        HttpClient.newBuilder().build().sendAsync(builder.build(), BodyHandlers.ofByteArray());

        Thread.sleep(Duration.ofSeconds(3).toMillis()); // (give Server time to serve!!)

        System.out.println(IppServer.logPrefix() + "IppClient Posted... (async)");
    }
}

Server Source:

package de.ipp.client.server;

import java.io.*;
import java.net.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;

public class IppServer {

    private static final DateTimeFormatter HH_MM_SS_NANOS = DateTimeFormatter.ofPattern("HH.mm.ss.SSSSSSSSS' '");

    public  static final int PORT = 31613;

    public  static void main(final String[] args) throws IOException {
        Thread.currentThread().setName("LISTENER");

        System        .out.println(logPrefix() + "IppServer Start....");

        try(final ServerSocket serverSocket = new ServerSocket(PORT))
        {
            System    .out.println(logPrefix() + "IppServer Running.: " + serverSocket);

            while (true) {
                final Socket socket = serverSocket.accept();

                System.out.println(logPrefix() + "IppServer Socket..: incoming -> " + socket);

                final Thread thread = new Thread(getSocketRunnable(socket));
                ;            thread.setDaemon(true);
                ;            thread.start();
            }
        }
    }

    private static Runnable getSocketRunnable(final Socket socket) {
        return () -> {
            try(final InputStream ist   = socket.getInputStream())
            {
                System.out.println(logPrefix() + "IppServer Reading..");

                final byte[]      buf   = new byte[4096];
                ;     int         count;

                while ((count = ist.read(buf)) != -1) {
                    logBytes(buf, count);

                    if (0 == Arrays.compare(buf, 0, count, IppClient.PAYLOAD, 0, IppClient.PAYLOAD.length)) {
                        /*
                         * For our purposes, it is sufficient that the payload was received OK.
                         * We do not need to complete the HTTP Handshake, so just break off the dialogue...
                         */
                        break;
                    }
                }
            }
            catch (final IOException e) {
                System.out.println(logPrefix() + "IppServer Error!!.: " + e.getMessage());
            }
        };
    }

    private static void logBytes(final byte[] bytes, final int count) {

        final StringBuilder sbd = new StringBuilder(count * 2);
        ;     byte          b;

        for (int i=0; i < count; i++) {
            b = bytes[i];

            if (b > 32   ) {sbd.append( (char) b);  continue;}

            if (b == '\r') {sbd.append("[\\r]");    continue;}
            if (b == '\n') {sbd.append("[\\n]");    continue;}

            sbd.append("[0x").append(Integer.toHexString(b)).append(']');
        }
        System.out.println(logPrefix() + "IppServer Bytes...: L=" + count + '\t' + sbd.toString());
    }

    public static String logPrefix() {
        return '[' + Thread.currentThread().getName() + "] " + HH_MM_SS_NANOS.format(LocalDateTime.now());
    }
}

Logs:

[LISTENER] 08.49.25.232446900 IppServer Start....
[LISTENER] 08.49.25.261367100 IppServer Running.: ServerSocket[addr=0.0.0.0/0.0.0.0,localport=31613]
[LISTENER] 08.49.38.749640100 IppServer Socket..: incoming -> Socket[addr=/127.0.0.1,port=65073,localport=31613]
[Thread-0] 08.49.38.753629400 IppServer Reading..
[Thread-0] 08.49.38.776568000 IppServer Bytes...: L=246 POST[0x20]/printers[0x20]HTTP/1.1[\r][\n]Connection:[0x20]Upgrade,[0x20]HTTP2-Settings[\r][\n]Content-Length:[0x20]9[\r][\n]Host:[0x20]localhost:31613[\r][\n]HTTP2-Settings:[0x20]AAEAAEAAAAIAAAABAAMAAABkAAQBAAAAAAUAAEAA[\r][\n]Upgrade:[0x20]h2c[\r][\n]User-Agent:[0x20]Java-http-client/17.0.1[\r][\n]Content-Type:[0x20]application/ipp[\r][\n][\r][\n]
[Thread-0] 08.49.38.780556300 IppServer Bytes...: L=9   SomeBytes
[LISTENER] 08.50.22.853368800 IppServer Socket..: incoming -> Socket[addr=/127.0.0.1,port=65091,localport=31613]
[Thread-1] 08.50.22.854365100 IppServer Reading..
[Thread-1] 08.50.22.880294200 IppServer Bytes...: L=246 POST[0x20]/printers[0x20]HTTP/1.1[\r][\n]Connection:[0x20]Upgrade,[0x20]HTTP2-Settings[\r][\n]Content-Length:[0x20]9[\r][\n]Host:[0x20]localhost:31613[\r][\n]HTTP2-Settings:[0x20]AAEAAEAAAAIAAAABAAMAAABkAAQBAAAAAAUAAEAA[\r][\n]Upgrade:[0x20]h2c[\r][\n]User-Agent:[0x20]Java-http-client/17.0.1[\r][\n]Content-Type:[0x20]application/ipp[\r][\n][\r][\n]
[Thread-1] 08.50.22.885280900 IppServer Bytes...: L=9   SomeBytes
[LISTENER] 09.01.07.880173600 IppServer Socket..: incoming -> Socket[addr=/127.0.0.1,port=65397,localport=31613]
[Thread-2] 09.01.07.881169400 IppServer Reading..
[Thread-2] 09.01.07.908097800 IppServer Bytes...: L=246 POST[0x20]/printers[0x20]HTTP/1.1[\r][\n]Connection:[0x20]Upgrade,[0x20]HTTP2-Settings[\r][\n]Content-Length:[0x20]9[\r][\n]Host:[0x20]localhost:31613[\r][\n]HTTP2-Settings:[0x20]AAEAAEAAAAIAAAABAAMAAABkAAQBAAAAAAUAAEAA[\r][\n]Upgrade:[0x20]h2c[\r][\n]User-Agent:[0x20]Java-http-client/17.0.1[\r][\n]Content-Type:[0x20]application/ipp[\r][\n][\r][\n]
[Thread-2] 09.01.07.914083500 IppServer Bytes...: L=9   SomeBytes

[myClient] 09.01.06.956313800 IppClient Posting.: http://localhost:31613/printers
[myClient] 09.01.10.783634700 IppClient Posted... (async)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文