【发布时间】:2018-11-03 11:19:33
【问题描述】:
这只是一个练习。 我想知道是否有与此代码等效的代码:
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 for URL:https://api.ciscospark.com/v1/rooms 401 身份验证凭据丢失或不正确。 我可以使用 printwriter 使其工作吗? 如果不是,为什么? 谢谢
【问题讨论】:
-
如果您手动编写 HTTP 请求,则不能使用 HttpsURLConnection(您的代码将请求写入服务器不解析的 HTTP 正文)。请改用原始 TCP 套接字。
-
如果我使用原始 TCP 套接字,我应该手动实现握手吗? (我认为)
-
什么握手?如果您使用 Socket/SSLSocket,您将获得一个 TCP 连接,您可以在该连接上获得 InputStream/OutputStream。
-
我尝试了 final SocketFactory socketFactory = SSLSocketFactory.getDefault(); String ipAddr = InetAddress.getByName("api.ciscospark.com/v1/rooms").toString(); 但给了我 java.net.UnknownHostException: api.ciscospark.com/v1/rooms: 未知错误...即使使用 nskookup 我也无法检索 ip...如果我制作 Socket 套接字= socketFactory.createSocket("api.ciscospark.com/v1/rooms", 443)) 表示未知主机
-
只使用主机名而不是完整的url(只是
/之前的部分)。
标签: java https httpsurlconnection webex