0

这只是一个练习。我想知道是否有与此代码等效的代码:

String https_url = "https://api.ciscospark.com/v1/rooms";
URL url = new URL(https_url);
HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();

connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); 
connection.setRequestProperty("Authorization", "I3MDUtMmEy");
connection.setDoOutput(true);

我认为可以制作类似的东西:

String https_url = "https://api.ciscospark.com/v1/rooms";
        URL url = new URL(https_url);
        HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
        connection.setDoOutput(true);
        PrintWriter pw = new PrintWriter(connection.getOutputStream());
        pw.println("GET /v1/rooms HTTP/1.1");
        pw.println("Host: https://api.ciscospark.com");
        pw.println("Content-Type: application/json; charset=utf-8");
        pw.println("Authorization: I3MDUtMmEy");
        pw.println("");

但我收到来自服务器返回的 HTTP 响应代码的身份验证错误消息:URL 为 401:https ://api.ciscospark.com/v1/rooms 401 身份验证凭据丢失或不正确。我可以使用 printwriter 使其工作吗?如果不是,为什么?谢谢

4

1 回答 1

0

我尝试过:

    private static void useSslSocket() throws IOException {
        final SocketFactory socketFactory = SSLSocketFactory.getDefault();
        String ipAddr = InetAddress.getByName("api.ciscospark.com").toString();
        System.out.println("IP: "+ipAddr);
        try (final Socket socket = socketFactory.createSocket("api.ciscospark.com", 80)) {
            final String request = "GET / HTTP/1.1\r\nConnection: close\r\nHost:stackoverflow.com\r\n\r\n";

            PrintWriter pw = new PrintWriter(socket.getOutputStream());



            pw.println("GET /v1/rooms HTTP/1.1");
            pw.println("Host: https://api.ciscospark.com");
            pw.println("Content-Type: application/json; charset=utf-8");
            pw.println("Authorization: I3MDUtMmEy");
            pw.println("");
//          pw.flush();
//          pw.close();

            final InputStream inputStream = socket.getInputStream();
            final String response = readAsString(inputStream);
            System.out.println(response);
        }
    }

响应 javax.net.ssl.SSLException:无法识别的 SSL 消息,明文连接?

于 2018-11-04T14:17:25.310 回答