<address id="ousso"></address>
<form id="ousso"><track id="ousso"><big id="ousso"></big></track></form>
  1. JAVA請求需要Basic身份驗證的網頁

    時間:2024-09-25 04:15:44 SUN認證 我要投稿
    • 相關推薦

    關于JAVA請求需要Basic身份驗證的網頁

      通過JAVA抓取頁面時,有些頁面會返回401(Unauthorized)響應狀態碼和www-authenticate響應頭來要求客戶端進行身份認證。這種認證有兩種方式:BASIC和DIGEST,BASIC驗證要求客戶端對用戶名和密碼進行BASE64編碼后傳送給服務器。DIGEST的認證方式的細節比較復雜,會經過一系列的加密,所以很難被破譯。

      JAVA提供一個用于啟用身份認證的類,可以支持HTTP協議中的多個認證方式,這個類是java.net.Authenticator,使用方法如下:

      Java 代碼

      1.package com.xixuyishi;

      2.

      3.import java.io.BufferedReader;

      4.import java.io.InputStream;

      5.import java.io.InputStreamReader;

      6.import java.net.Authenticator;

      7.import java.net.PasswordAuthentication;

      8.import java.net.URL;

      9.

      10.public class RunHttpSpnego {

      11.

      12. static final String kuser = "username"; // 用戶名

      13. static final String kpass = "password"; // 密碼

      14. static class MyAuthenticator extends Authenticator {

      15.

      16. @Override

      17. public PasswordAuthentication getPasswordAuthentication() {

      18. return (new PasswordAuthentication(kuser, kpass.toCharArray()));

      19. }

      20. }

      21.

      22. public static void main(String[] args) throws Exception {

      23. Authenticator.setDefault(new MyAuthenticator());

      24. URL url = new URL(args[0]);

      25. InputStream ins = url.openConnection().getInputStream();

      26. BufferedReader reader = new BufferedReader(new InputStreamReader(ins));

      27. String str;

      28. while ((str = reader.readLine()) != null)

      29. System.out.println(str);

      30. }

      31.}

      只需要創建一個繼續自Authenticator的類,并且重寫其中的getPasswordAuthentication()方法,將用戶名和密碼放入方法中,這樣在需要使用身份認證的地方實現這個類就可以了。

    【JAVA請求需要Basic身份驗證的網頁】相關文章:

    網頁美工需要掌握哪些電腦常識03-18

    網頁美工設計需要注意的細節03-13

    如何透過客戶表面請求來滿足其實質需要03-22

    談談網頁美工設計需要注意的三大細節03-20

    PHP如何通過會話控制實現身份驗證03-29

    日語語法之請求的表達03-09

    網頁美工必備的知識:網頁設計命名規范03-18

    學習Java的技巧03-05

    java習題及答案03-26

    <address id="ousso"></address>
    <form id="ousso"><track id="ousso"><big id="ousso"></big></track></form>
    1. 日日做夜狠狠爱欧美黑人