title: Java Junit test HTTP POST request
body: <p>I need to test the following method with out altering the method itself.
  The method makes a POST method to a server. But I need to make a test case that's independent  from the server.</p>
  
  <p>I tested a similar method before redirecting it to a local file.
  But that for that I was giving protocol as file, hostname as localhost and port as -1.</p>
  
  <p>My problem is that this method does a post and casts to HttpURLConnection and wr = new DataOutputStream(conn.getOutputStream()); wont work on an local txt file through http.</p>
  
  <p>//the constructor</p>
  
  <pre><code>public HTTPConnector(String usr, String pwd, String protocol,
              String hostname, int port) {
          this.usr = usr;
          this.pwd = pwd;
          this.protocol = protocol;
          this.hostname = hostname;
          this.port = port;
  
          // connect();
      }
  </code></pre>
  
  <p>//the method I need to test</p>
  
  <pre><code>public String doPost(String reference, String data) throws IOException {
          URL url = null;
          HttpURLConnection conn = null;
          BufferedReader rd = null;
          DataOutputStream wr = null;
          InputStream is = null;
          String line = null;
          StringBuffer response = null;
  
          url = new URL(protocol, hostname, port, reference);
          conn = (HttpURLConnection) url.openConnection();
  
          conn.setRequestMethod("POST");
  
          conn.setRequestProperty("Authorization", "Basic dGVzdDphc2Rm");
          conn.setRequestProperty("Content-Type", "application/xml");
  
          conn.setUseCaches(false);
          conn.setDoInput(true);
          conn.setDoOutput(true);
  
          // Send response
          wr = new DataOutputStream(conn.getOutputStream());
          wr.writeBytes(data);
          wr.flush();
          wr.close();
  
          // Get response
          is = conn.getInputStream();
          rd = new BufferedReader(new InputStreamReader(is));
          response = new StringBuffer();
          while ((line = rd.readLine()) != null) {
              response.append(line);
              response.append('\r');
          }
          rd.close();
          return response.toString();
      }
  </code></pre>
  
  <p>//the method I could test</p>
  
  <pre><code>public String doGet(String reference) throws IOException {
          connect();
          URL url = new URL(protocol, hostname, port, reference);
          InputStream content = (InputStream) url.getContent();
  
          BufferedReader xml = new BufferedReader(new InputStreamReader(content));
          return xml.readLine();
      }
  </code></pre>