首页 > 解决方案 > 当身份验证凭据正确时,http post 请求返回 401 -

问题描述

我仅在发布数据时遇到此问题,我得到了 401(未经授权),而我的凭证是正确的!如何解决这个问题?

ttpURLConnection urlConnection;
       IgnoreSSL();
       String url = null;
       url = "http://" + nmap_node.getHost() + ":"+nmap_node.getPort() + "/post";
       String result = null;
       try {

           String userpass = user_name + ":" + password; //stored in the class
           String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));

           //Connect
           urlConnection = (HttpURLConnection) ((new URL(url).openConnection()));
           urlConnection.setDoOutput(true);
           urlConnection.setRequestProperty("Content-Type", "application/json");
           urlConnection.setRequestProperty("Authorization", "Basic "+basicAuth);
           urlConnection.setRequestProperty("Accept", "application/json");
           urlConnection.setRequestMethod("POST");
           urlConnection.setConnectTimeout(10000);
           urlConnection.connect();
           //data
           String data = datajson.toString(); //method return json to use
           OutputStream outputStream = urlConnection.getOutputStream();
           BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
           writer.write(data);
           writer.close();
           outputStream.close();
           int responseCode=urlConnection.getResponseCode();
           if (responseCode == HttpsURLConnection.HTTP_OK) {
               //Read
               BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));

               String line = null;
               StringBuilder sb = new StringBuilder();

               while ((line = bufferedReader.readLine()) != null) {
                   sb.append(line);
               }

               bufferedReader.close();
               result = sb.toString();

           }else {
               //    return new String("false : "+responseCode);
               new String("false : "+responseCode);
           }

       } catch (UnsupportedEncodingException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       }

我在 Linux 中尝试使用 curl 命令它运行良好 - 我得到响应 200 并在屏幕上打印结果。

标签: javapost

解决方案


推荐阅读