如何在Java中使用HttpURLConnection?(Http Digest)

时间:2018-06-04 10:37:04

标签: java httpurlconnection

早上好。我有一个关于Java HttpURLConnection的问题。

我使用IP摄像头和HTTP摘要来控制IP摄像头PTZ。

首先连接到以下源,然后尝试再次使用nonce值,领域值和我的信息重新进行身份验证时,出现401(未授权)错误消息。

    // IpCamera PTZ URI
    String url = "http://192.168.2.21/cgi-bin/ptzmove.cgi?move=left";

    try{

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    con.setRequestMethod("GET");        
    con.setRequestProperty("Accept", "text/html/, application.xhtml+xml, image/jxr, */*");
    con.setRequestProperty("Accept-Language", "ko-KR");
    con.setRequestProperty("User-Agent", "KSyncViewM/1.0 (Test Version)");
    con.setRequestProperty("Accept_encoding", "gzip, deflate");

    System.out.println(con.getResponseCode());

重新授权的

    if(con.getResponseCode() == 401){           

        //HttpURLConnection con1 = (HttpURLConnection)obj.openConnection();

        //  UnAuthorized
        if(digestMap.get("qop") != null
            && (digestMap.get("qop").compareTo("auth") == 0
            || digestMap.get("qop").compareTo("auth-int") == 0)){

            String val = "00000001";

            String a1 = A1("admin", digestMap.get("realm"), "Password");
            String a2 = A2("GET", "/cgi-bin/ptzmove.cgi?move=left");
            String response = RequestDigest(a1, digestMap.get("nonce"), val, mCnonce, digestMap.get("qop"), a2);



            //con1.setRequestMethod("GET"); 
                            // throw java.lang.IllegalStateException(Already connected)
            con.setRequestProperty("Accept", "text/html/, application.xhtml+xml, image/jxr, */*");
            con.setRequestProperty("Accept-Language", "ko-KR");
            con.setRequestProperty("User-Agent", "Test/1.0 (Test Version)");
            con.setRequestProperty("Accept_encoding", "gzip, deflate");

            con.setRequestProperty("Authorization", 
                    " Digest username=\"admin\",realm=\"" + digestMap.get("realm") + "\","
                    + "nonce=\"" + digestMap.get("nonce") + "\","
                    + "uri=\"//cgi-bin/ptzmove.cgi?move=left\","
                    + "cnonce=\"" + mCnonce + "\",nc=00000001,"
                    + "response=\"" + response + "\","
                    + "qop=\"" + digestMap.get("qop") + "\"");



            System.out.println(con.getResponseCode());
        }

问题是,在收到响应之后,如果我重新配置信息然后设置信息以将其发送回HttpURLConnection对象,则会出现Already Connection错误。 (当然,HttpURLConnection对象告诉我们在写完后写TCP。)

那么如何获得401消息,然后在维护会话时重新进行身份验证?

0 个答案:

没有答案