简体   繁体   中英

HttpClient authentication -

I am trying to emulate this behavior in java

curl -u usrname:password http://somewebsite.com/docs/DOC-2264

I am not sure if the auth is NTLM or Basic. I login to the website giving a username and passoword. It's a form post. Using the curl command above I am able to login and get the content.

To do this in java I did:

    try {
        URL url = new URL("http://somewebsite.com/docs/DOC-2264");
        String authStr ="username:password";
        String encodedAuthStr = Base64.encodeBytes(authStr.getBytes());
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        onnection.setRequestProperty("Authorization", "Basic" + encodedAuthStr);

        InputStream content = (InputStream)connection.getInputStream();
        BufferedReader in   = 
            new BufferedReader (new InputStreamReader (content));
        String line;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }           


    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

But I only get the login page. Not the actual content. What am i doing wrong?

  1. You can see the exact header curl is sending by adding the -v (verbose) option.
  2. The Authorization header needs the authentication type before the base64 encoded username/password. It should look something like this: Authorization: Basic dXNybmFtZTpwYXNzd29yZA==

也许curl可以做到这一点:

URL url = new URL("http://username:password@somewebsite.com/docs/DOC-2264");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM