PrintWriter中的java HttpsURLConnection setRequestProperty等效项

时间:2018-11-03 11:19:33

标签: java https httpsurlconnection webex

这只是一种练习。 我想知道这段代码是否等效:

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响应代码:401的auth错误消息,URL:https://api.ciscospark.com/v1/rooms 401身份验证凭据丢失或不正确。 我可以使用printwriter使其工作吗? 如果没有,为什么? 谢谢

1 个答案:

答案 0 :(得分: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消息,纯文本连接?