Search code examples
javaeclipsepostget

Java - sending POST


I'm trying to make java make a new addition to a url shortener, here's what I have:

private void sendPost() throws Exception {

    String url = "http://shmkane.com/index.php?";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    String urlParameters = "url=testingThis";

    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();

    System.out.println(response.toString());

}

I'd like for it to put something in "form1" and then "submit"

I'm very new to this so any help would be great, possible tell me what I'm doing wrong or improving/fixing the code I currently have.


Solution

  • That site doesn't support post:

    <form method="get" id="form1" action="index.php">
        <p>&nbsp;</p>
        <p><br>
          <input class="textBox" id="url" placeholder="Paste a link to shorten it" type="text" name="url" value="">
        </p>
        <p>
          <input class="textBox" placeholder="Custom alias" id="alias" maxlength="15" type="text" name="alias" value="">
        </p>
        <div class="button">
          <p>
            <input class="button" type="submit" value="Shorten">
          </p>
    <br>
          <div class="alert-box success">
            <center>
              <a href="" target="_blank"></a>
            </center>
          </div>
          <em>May only contain letters, numbers, dashes and underscores.</em>
          <p></p>
        </div>
      </form>
    

    Notice the method is GET. Change to this:

     String urlParameters = "url=testingThis";
     String url = "http://shmkane.com/index.php?";
     URL obj = new URL(url + urlParameters);
     HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    
     con.setRequestMethod("GET");
    

    And get rid of the writing to the output stream.