将摘要身份验证添加到 POST (Java)

时间:2020-12-28 10:09:29

标签: java authentication

使用以下代码运行良好,直到我遇到需要摘要式身份验证(用户名管理员、密码 PASSWORD)的设备。

public static String excutePost(final String targetURL, final String urlParameters) {
        HttpURLConnection connection = null;
        try {
            final URL url = new URL(targetURL);
            connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
            connection.setRequestProperty("Content-Language", "en-US");
            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            final DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();
            final InputStream is = connection.getInputStream();
            final BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            final StringBuffer response = new StringBuffer();
            String line;
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();
            return response.toString();
        }
        catch (Exception e) {
            Logger.logFile("HIGH", "ERROR", "ArtNodeDriver", "executePost", e.getMessage());
            e.printStackTrace();
            return null;
        }
        finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

我查看了各种摘要认证帖子,它们看起来都非常复杂,是否有使用库或其他东西的“更简单的方法”?

我有一个运行良好的 cURL 命令 -

Curl --digest -u admin:PASSWORD -X POST -d "group=CPM CPs&optionalItem=CP&optionalItemInstance=1&action=Value 1" http://192.168.150.210/action/status

但我不知道您是否可以或应该“在 Java 中运行 cURL”。

思想赞赏。 拉尔夫

0 个答案:

没有答案