title: Java: how to use UrlConnection to post request with authorization?
body: <p>I would like to generate POST request to a server which requires authentication. I tried to use the following method:</p>
  
  <pre><code>private synchronized String CreateNewProductPOST (String urlString, String encodedString, String title, String content, Double price, String tags) {
  
      String data = "product[title]=" + URLEncoder.encode(title) +
                  "&amp;product[content]=" + URLEncoder.encode(content) + 
                  "&amp;product[price]=" + URLEncoder.encode(price.toString()) +
                  "&amp;tags=" + tags;
      try {
          URL url = new URL(urlString);
          URLConnection conn;
          conn = url.openConnection();
          conn.setRequestProperty ("Authorization", "Basic " + encodedString);
          conn.setDoOutput(true);
          conn.setDoInput(true);
          OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
          wr.write(data);
          wr.flush(); 
          // Get the response 
          BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
          String line; 
          while ((line = rd.readLine()) != null) { 
              // Process line... 
              } 
          wr.close(); 
          rd.close(); 
          return rd.toString();
      } catch (MalformedURLException e) {
  
          e.printStackTrace();
          return e.getMessage();
      }
      catch (IOException e) {
  
          e.printStackTrace();
          return e.getMessage();
      } 
  }
  </code></pre>
  
  <p>but the server doesn't receive the authorization data. The line which is supposed to add authorization data is the following:</p>
  
  <pre><code>conn.setRequestProperty ("Authorization", "Basic " + encodedString);
  </code></pre>
  
  <p>and the line </p>
  
  <pre><code>BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
  </code></pre>
  
  <p>also throws an IOException.</p>
  
  <p>Anyway I would be very thankful if anyone could suggest any fix of the logic above in order to enable authorization using POST with UrlConnection.</p>
  
  <p>but obviously it doesn't work as it is supposed to although if the same logic is used for GET request everything works fine.</p>