title: Java Server returned HTTP response code: 401
body: <p>Hi I write java program to do a http post request by Http Basic Authentication
  but it always shows error 401. My username and password is right can login the website. I don't know where wrong?</p>
  
  <pre><code> import java.io.BufferedReader;
   import java.io.DataOutputStream;
   import java.io.InputStreamReader;
   import java.net.HttpURLConnection;
   import java.net.URL;
   import sun.misc.*;
  
   import javax.net.ssl.HttpsURLConnection;
   import org.apache.commons.codec.*;
  
   @SuppressWarnings("unused")
   public class hello {
  
  /**
   * @param args
   */
  private final String USER_AGENT = "Mozilla/5.0";
  public static void main(String[] args) throws Exception {
      // TODO Auto-generated method stub
      hello http = new hello();
  
  
      //System.out.println("Testing 1 - Send Http GET request");
      //http.sendGet();
  
      System.out.println("\nTesting 2 - Send Http POST request");
      http.sendPost();
  }
  
  @SuppressWarnings("unused")
  private void sendPost() throws Exception {
  
      String url = "https://mds.datacite.org/doi";
      URL obj = new URL(url);
      HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
      String userPassword= "username:password";
      String encoding = new String(org.apache.commons.codec.binary.Base64.encodeBase64(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(userPassword)));
      System.out.println(encoding);
  
  
      //add reuqest header
      con.setRequestMethod("POST");
      con.setRequestProperty("Content-Type", "text/plain");
      con.setRequestProperty("charset", "UTF-8");
      con.setRequestProperty("Authorization","Basic"+encoding);
  
  
      String urlParameters = "doi=xxxxxx&amp;url=http://xxxxx/dataset/1xxx099";
  
      // Send post request
      con.setDoOutput(true);
      DataOutputStream wr = new DataOutputStream(con.getOutputStream());
      wr.writeBytes(urlParameters);
      wr.flush();
      wr.close();
  
      int responseCode = con.getResponseCode();
      System.out.println("\nSending 'POST' request to URL : " + url);
      System.out.println("Post parameters : " + urlParameters);
      System.out.println("Response Code : " + responseCode);
  
      BufferedReader in = new BufferedReader(
              new InputStreamReader(con.getInputStream()));
      String inputLine;
      StringBuffer response = new StringBuffer();
  
      while ((inputLine = in.readLine()) != null) {
          response.append(inputLine);
      }
      in.close();
  
      //print result
      System.out.println(response.toString());
  
  }
  </code></pre>