0

I have a command line:

curl -u username:passwd -k "https://myserver/a/b/c"

It works and I will get right information when I call it under Ubuntu or Cygwin.

Now I am willing to accomplish it in Java. So I have Java code like that:

    public class Test {

    public static String auth = "username:passwd";
    public static String url = "https:/myserver/a/b/c";

    public static void main(String[] args) {
        try {
            URL url = new URL(url);
            final byte[] authBytes = auth.getBytes(StandardCharsets.UTF_8);
            String encoding = java.util.Base64.getEncoder().encodeToString(authBytes);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

            connection.setRequestMethod("POST");

            connection.setRequestProperty("Authorization", encoding);

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            String line;

            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

But It seems not work and always return HTTP response code 411. Is there something wrong with the java code?

Thanks in advanced.

2
  • You're doing a POST but not sending anything. Is that what curl does? Otherwise you're comparing apples and oranges. Commented Dec 22, 2015 at 5:38
  • The curl command makes a GET... Commented Dec 22, 2015 at 7:21

1 Answer 1

1

HTTP response code 411 means that "The server refuses to accept the request without a defined Content- Length."

http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

HttpsUrlConnection should be able to do that for you. Check out setFixedLengthStreamingMode(). I think you will also need to setDoOutput().

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much. I am willing to add setDoOutput(true) and setFixedLengthStreamingMode (int contentLength) . But I don't know hot to set parameter contentLength. I gave it some random values and just got IOException: insufficient data written. I also tired setChunkedStreamingMode, but still cannot work.
You have to set it to the length of the data you write, which is zero.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.