如何通过Java在HTTPS中正确发送POST?

时间:2019-04-12 17:22:39

标签: java https

我正在用Java编写游戏的mod,以检查玩家是否已使用服务器方法投票以获取Steam ID。我所看到的没有得到很好的回应。每个响应都是一个IOException,我已经打印出了“无效的响应代码”。

我已经尝试实现在https连接的类似mod中看到的内容,但是我却一无所获。

try {
  HttpsURLConnection connection = (HttpsURLConnection) new URL(             "https://somewebsite.com/"
                ).openConnection();
                connection.setSSLSocketFactory(createTrustAllSocketFactory());

                int responseCode = connection.getResponseCode();
                if (responseCode != 200) throw new IOException("Invalid response code.");

                InputStream in = connection.getInputStream();

                ByteArrayOutputStream stringBuffer = new ByteArrayOutputStream();
                byte[] buffer = new byte[256];
                int len = 0;
                while (len != -1) {
                    stringBuffer.write(buffer, 0, len);
                    len = in.read(buffer);
                }

                String result = new String(stringBuffer.toByteArray(), StandardCharsets.UTF_8);
                if (result.equals("1")) {
                    try {
                        performer.addMoney(MonetaryConstants.COIN_COPPER * 5);
                        performer.getCommunicator().sendNormalServerMessage("Thanks for voting! Your rewards have been added to your bank.");
                    } catch (IOException ex) {
                        performer.getCommunicator().sendAlertServerMessage("Failed to add reward. Please submit a support ticket.");
                        ex.printStackTrace();
                    }
                }

private static SSLSocketFactory createTrustAllSocketFactory() throws IOException {
                try {
                    SSLContext ctx = SSLContext.getInstance("TLS");
                    TrustManager[] trustManagers = {
                            new X509TrustManager() {
                                @Override
                                public void checkClientTrusted(X509Certificate[] chain, String authType) {
                                    /* empty */
                                }

                                @Override
                                public void checkServerTrusted(X509Certificate[] chain, String authType) {
                                    /* empty */
                                }

                                @Override
                                public X509Certificate[] getAcceptedIssuers() {
                                    return new X509Certificate[0];
                                }
                            }
                    };
                    ctx.init(null, trustManagers, null);
                    return ctx.getSocketFactory();
                } catch (GeneralSecurityException ex) {
                    throw new IOException(ex);
                }
            }

期望的是,当在游戏中发出命令时,服务器将使用玩家的Steam ID调用外部站点,并根据他们是否投票来生成0或1。

Actual收到错误的响应代码。

0 个答案:

没有答案