Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
通过Java发送Https请求,但收到未经授权的错误-401_Java_Web Services - Fatal编程技术网

通过Java发送Https请求,但收到未经授权的错误-401

通过Java发送Https请求,但收到未经授权的错误-401,java,web-services,Java,Web Services,我通过两种方式发送带有用户名和密码的Https请求,但在这两种情况下,我都会收到错误401-未经授权的错误 通过URLConnection直接连接 try { URL url = new URL("https://xxx.xxxxx.com/v1/limit/5"); URLConnection urlConnection = url.openConnection(); HttpsURLConnection connection = null; if(urlCon

我通过两种方式发送带有用户名和密码的Https请求,但在这两种情况下,我都会收到错误401-未经授权的错误

  • 通过URLConnection直接连接

    try {
        URL url = new URL("https://xxx.xxxxx.com/v1/limit/5");
        URLConnection urlConnection = url.openConnection();
        HttpsURLConnection connection = null;
        if(urlConnection instanceof HttpsURLConnection) {
            String authStr = "username"+":"+"password";
            byte[] bytesEncoded = Base64.encodeBase64(authStr.getBytes());
            String authEncoded = new String(bytesEncoded);
            connection = (HttpsURLConnection) url.openConnection();
            connection.setRequestProperty("Authorization", "Basic "+authEncoded);
         } else {
             System.out.println("Please enter an HTTPs URL.");
             return;
         }
    
         BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
         String urlString = "";
         String current;
         while((current = in.readLine()) != null) {
             urlString += current;
         }
         System.out.println(urlString);
    } catch(IOException e) {
        e.printStackTrace();
    }
    
  • 通过Jersey客户端进行连接,但以相同的方式,我收到401 unauth错误


  • 因为它在这些情况下都不起作用:有没有可能,您实际上是未经授权的,或者没有使用正确的身份验证机制?我检查了Postman rest客户端的相同凭据,API工作正常。我不确定我是否遗漏了什么如果你使用的是Postman,你可以使用它的“生成代码”功能。应该很容易找到URL中任何缺少的标题(接受、内容类型)或差异。的可能重复项