How to form a proper HTTP POST request with a cookie to log in YouTrack (from Java application)?

Could someone please tell me how to write a proper POST request with a cookie to log in YouTrack and get the "JSESSIONID" cookie from Java application? The way to do this described at this piece of official documentation. Here is the copy:
POST http://localhost:8081/rest/user/login
Content-Length: 24
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded


I wrote a POST request but I'm getting server error 400 instead of
HTTP/1.1 200 OK
Expires: Thu, 01-Jan-1970 00:00:00 GMT
Set-Cookie: JSESSIONID=n7hq7t8o49ae15sgbq5hn9ic;Path=/
Set-Cookie:;Path=/;Expires=Thu, 12-May-2011 16:37:10 GMT
Content-Type: application/xml;charset=UTF-8
Transfer-Encoding: chunked
Server: Jetty(6.1.23)

Here is my code:
URL url = new URL(webPage); 
            URLConnection urlc = (HttpURLConnection) url.openConnection();
            ((HttpURLConnection) urlc).setRequestMethod("POST");
            urlc.setRequestProperty("Content-Length", Integer.toString(24));
            urlc.setRequestProperty("Connection", "keep-alive");
            urlc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            String myCookie = "login=root&password=root";
            urlc.setRequestProperty("Cookie", myCookie);

            InputStream is = urlc.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);

            int numCharsRead;
            char[] charArray = new char[1024];
            StringBuffer sb = new StringBuffer();
            while ((numCharsRead = > 0) {
 sb.append(charArray, 0, numCharsRead);
            String result = sb.toString();

            System.out.println("result = " + result); 

What am I doing wrong? Thank you.
Comment actions Permalink
You set the cookie to be the login information, but the login information should be in the body of the request.

See e.g.
Comment actions Permalink
Here is the working piece of code

   HttpClient client = HttpClientBuilder.create().build();
                  MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create()
                          .addTextBody("login", "root").addTextBody("password", "root");
                  HttpEntity entity =;
                  HttpPost post = new HttpPost(webPage);
                  HttpResponse response = client.execute(post);

Please sign in to leave a comment.