title: Posting to a webservice using httpurlconnection
body: <p>How come I am only allowed to make posts to .com url's but not .asmx url's? Im a bit confused as what I want to generally do is send xml content to a .asmx url web service eventually. Can anyone supply me with tips why this doesn't work, and how I can post to a .asmx file?</p>
  
  <pre><code>public class POSTSenderExample {
  
  
      public String echoCuties(String query) throws IOException {
          // Encode the query
          String encodedQuery = URLEncoder.encode(query, "UTF-8");
          // This is the data that is going to be send to itcuties.com via POST request
          // 'e' parameter contains data to echo
          String postData = "e=" + encodedQuery;
  
  
          URL url = new URL("http://echo.itgeeeks.asmx");
          HttpURLConnection connection = (HttpURLConnection) url.openConnection();
          connection.setDoOutput(true);
          connection.setRequestMethod("POST");
          connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
          connection.setRequestProperty("Content-Length",  String.valueOf(postData.length()));
  
          // Write data
          OutputStream os = connection.getOutputStream();
          os.write(postData.getBytes());
  
          // Read response
          StringBuilder responseSB = new StringBuilder();
          BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  
          String line;
          while ( (line = br.readLine()) != null)
              responseSB.append(line);
  
          // Close streams
          br.close();
          os.close();
  
          return responseSB.toString();
  
      }
  
      // Run this example
      public static void main(String[] args) {
          try {
  
              System.out.println(new POSTSenderExample().echoCuties("Hi there!"));
  
          } catch (IOException ioe) {
              ioe.printStackTrace();
          }
      }
  
  }
  </code></pre>