(JAVA)打开网址时出错,需要进行身份验证

时间:2017-12-20 11:24:05

标签: java authentication url

我正在使用此方法打开网址,并且工作正常

    String osName = System.getProperty("os.name");
    String url = "https://abcdefg.com";
    try {
        if (osName.startsWith("Windows")) {
            Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
        } else if (osName.startsWith("Mac OS X")) {
            Runtime.getRuntime().exec("open " + url);
        } else {
            System.out.println("SO unsupported");
        }
    } catch (IOException e) {
        System.out.println("Error opening " + url);
        e.printStackTrace();
    }

我现在的问题是我正在尝试输入一个需要在进入之前进行身份验证的URL(它给我错误403 Forbidden。您无权访问/在此服务器上)。问题是,在启动url之前我如何进行身份验证,所以我没有收到错误? (我有用户/通行证) link to the image, I cant post them yet...

提前致谢!

PD:我使用该方法打开一个网址,因为在有人要求之前,另一个人给了我这个错误:P

try {
    URL url = new URL("http://www.google.com");
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    //InputStream is = url.openConnection().getInputStream();
    //BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    String line = null;
    while ((line = in.readLine()) != null) {
        System.out.println(line);
    }
    in.close();     
} catch (MalformedURLException e) {
    System.out.println("MalformedURLException-> " + e);
} catch (IOException e) {
    System.out.println("IOException-> " + e);
}
  

IOException-> java.net.SocketException:连接重置

2 个答案:

答案 0 :(得分:0)

您必须验证您的Http请求,但这取决于服务器请求的身份验证方案。

通常,您必须从HttpUrlConnection创建URL,并使用正确的值设置Authentication标头。搜索Http身份验证。 像 basic 这样的一些Http身份验证方案很容易实现,但有些太复杂了,你应该使用给定的库。

答案 1 :(得分:0)

假设支持基本身份验证,我就是这样做的

static String readUrl(String url, String user, String pass) throws IOException {
    byte[] auth = (user + ':' + pass).getBytes("UTF-8");
    auth = Base64.getEncoder().encode(auth);

    URLConnection conn = new URL(url).openConnection();
    conn.setRequestProperty("Accept-Charset", "UTF-8");
    conn.setRequestProperty("Accept-Encoding", "identity");
    conn.setRequestProperty("User-Agent", "MadeUpUserAgent/0.1");
    conn.setRequestProperty("Authorization", "Basic " + new String(auth));

    StringBuilder sb = new StringBuilder();
    InputStream in = conn.getInputStream();
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(in, "UTF-8"));

    for (String line; (line = reader.readLine()) != null;) {
        sb.append(line).append(System.lineSeparator());
    }

    return sb.toString();
}