1

I am using the following code to send a REST request, the request is failed (401 error) because it needs username and password.

how to add them to the url ? even when I copy the url in browser and add the username and password to the end of it the browser pop out the login page, so I suppose in the code I should add the username and password parameters but how ?

  URL url = new URL("www.example.com/user?ID=1234");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
                if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
            throw new RuntimeException("Failed : HTTP error code : "
                + conn.getResponseCode());
        }

I added the following to the code but still run into 401 error.

             conn.setRequestProperty("username", "myusername");
             conn.setRequestProperty("password", "mypassword");
Daniel Morgan
  • 782
  • 5
  • 15
  • 43
  • 1
    [Check this out](http://stackoverflow.com/questions/9767952/how-to-add-parameters-to-httpurlconnection-using-post) – Rahul Mar 22 '13 at 04:29

1 Answers1

1

Try this:

String params="username=myusername&password=mypassword";
conn.getOutputStream().write(params.getBytes());
conn.getOutputStream().flush();
conn.getOutputStream().close();

Or maybe you need encode the params:

DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

String postContent = URLEncoder.encode("username", "UTF-8") + "=" + 
                     URLEncoder.encode(myusername, "UTF-8") + "&" + 
                     URLEncoder.encode("password", "UTF-8") + "=" + 
                     URLEncoder.encode(mypassword, "UTF-8") ;

dos.write(postContent.getBytes());
dos.flush();
dos.close();

About Basic Authorization

String userPassword = username + ":" + password;
String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes());
URLConnection uc = url.openConnection();
uc.setRequestProperty("Authorization", "Basic " + encoding);
uc.connect();
lichengwu
  • 4,277
  • 6
  • 29
  • 42