• 403,401 规格严格


    java.io.IOException: Server returned HTTP response code: 403 for URL

    但是自己却可以用浏览器访问,发现可能是服务器对我们这种java程序屏蔽了。

    因为服务器的安全设置不接受Java程序作为客户端访问,解决方案是设置客户端的User Agent

    url = new URL("url");
                HttpURLConnection connection = (HttpURLConnection) url.
                    openConnection();
                connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

    这样就可以访问了。

    ===========================================================================

    java.io.IOException: Server returned HTTP response code: 401 for URL

    // Install the custom authenticator
    Authenticator.setDefault(new MyAuthenticator());

    // Access the page
    try {
        // Create a URL for the desired page
        URL url = new URL("http://hostname/index.html");

        // Read all the text returned by the server
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String str;
        while ((str = in.readLine()) != null) {
            // str is one line of text; readLine() strips the newline character(s)
        }
        in.close();
    } catch (MalformedURLException e) {
    } catch (IOException e) {
    }

    public class MyAuthenticator extends Authenticator {
        // This method is called when a password-protected URL is accessed
        protected PasswordAuthentication getPasswordAuthentication() {
            // Get information about the request
            String promptString = getRequestingPrompt();
            String hostname = getRequestingHost();
            InetAddress ipaddr = getRequestingSite();
            int port = getRequestingPort();

            // Get the username from the user...
            String username = "myusername";

            // Get the password from the user...
            String password = "mypassword";

            // Return the information
            return new PasswordAuthentication(username, password.toCharArray());
        }
    }

  • 相关阅读:
    elasticsearch 基础 —— 集群原理
    剑指 offer set 10 栈的压入、弹出序列
    剑指 offer set 9 包含min函数的栈
    剑指 offer set 8 树的子结构
    剑指 offer set 7 调整数组顺序使奇数位于偶数前面
    剑指 offer set 6 打印从 1 到 N 的所有数
    剑指 offer set 5 二进制中 1 的个数
    剑指 offer set 4 矩形覆盖
    剑指 offer set 3 旋转数组的最小数字
    剑指 offer set 2 从头到尾打印链表
  • 原文地址:https://www.cnblogs.com/diyunpeng/p/1903669.html
Copyright © 2020-2023  润新知