HttpURLConnection and BASIC Authentication: FileNotFoundExceptio

Discussions

Web tier: servlets, JSP, Web frameworks: HttpURLConnection and BASIC Authentication: FileNotFoundExceptio

  1. Hi All,

    I am trying to use BASIC Authentication (using Base64 Encoding) to log into a Servlet hosted on a machine frmo a Java Client and am running into a few problems. Could someone please help me?I am getting :java.io.FileNotFoundException: Response: '401: Unauthorized xxx' for url: exeception message whenever i try to make the connection.Heres the code(I am trying Servlets.com's HttpMessage to se if it will work):

    public InputStream sendXMLPostMessage(LogF logF) throws IOException,MarshalException,ValidationException {
        HttpURLConnection con = (HttpURLConnection)servlet.openConnection();
        //set user interaction off
        con.setAllowUserInteraction(false);

        // Prepare for both input and output
        con.setDoInput(true);
        con.setDoOutput(true);

        // Turn off caching
        con.setUseCaches(false);

        // Set the content type to be text/xml
        //con.setRequestProperty("Content-Type",
        // "text/xml");
        
        // Work around a Netscape bug
        con.setRequestProperty("Content-Type",
                               "application/x-www-form-urlencoded");
        
        String authorization = name + ":" + password;
        String encodedAuthorization= new String(Base64.encodeBase64(authorization.getBytes()));
        log.debug("Encoded Authorization String for FinLitLog is :"+encodedAuthorization);
        con.setRequestProperty("Authorization", "Basic " + encodedAuthorization);
        // Marshall the object into XML using Castor and upload that XML as post data
        PrintWriter out =new PrintWriter(con.getOutputStream());
       //now write to the stream
        Marshaller.marshal(logF,out);
        
        out.flush();
        out.close();

        return con.getInputStream();
      }

    Could anyone please tell me what I am doing wrong?

    Thanks in advance for all the help!

    Vik.
  2. Hi.
    I do not know whether this works, but try to put this line

    con.connect();

    after your

    con.setRequestProperty("Authorization", "Basic " + encodedAuthorization);

    Good luck,

    Michael
  3. Hi,
      I am trying to replace com.Ostermiller.util.Base64 with
    org.apache.commons.codec.binary.Base64 I am not getting any error but it is failing to authenticate the user.
    If any one has tried please let me know.