0

I wrote a code for receiving the data but I don't know how to send the post data to the server.

package com.company;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {
    URL url;
    HttpURLConnection conn;

    try{
        url=new URL("http://mysite/create.php");

        String param="name=" + URLEncoder.encode("hello","UTF-8");

        conn=(HttpURLConnection)url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");

        conn.setFixedLengthStreamingMode(param.getBytes().length);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        PrintWriter out = new PrintWriter(conn.getOutputStream());
        out.print(param);
        out.close();

        String response= "";

        Scanner inStream = new Scanner(conn.getInputStream());

        while(inStream.hasNextLine())
            response+=(inStream.nextLine());

    }
    catch(MalformedURLException ex){


    }
    catch(IOException ex){


    }
}

}

But no response while executing it. I am running it IntelliJ Jetbrains IDE.

halfer
  • 19,824
  • 17
  • 99
  • 186
Krish
  • 3
  • 2
  • Try using BasicNameValuePair, like suggested in http://stackoverflow.com/questions/9767952/how-to-add-parameters-to-httpurlconnection-using-post – amupoti Sep 22 '15 at 14:16
  • But namevaluepair is deprecated@amupoti – Krish Sep 22 '15 at 14:23
  • 1
    Get rid of `catch(IOException ex){ }` and the other empty catch block and you might be able to figure out what's wrong – artbristol Sep 22 '15 at 16:04
  • 1
    even though no response. It is showing response code as 500 @artbristol – Krish Sep 22 '15 at 16:31
  • 1
    Um, 500 is not "no response", it's `internal server error`. At this point I'd check with the server folks, if possible, and maybe peek at their logs, if possible. It is not at all unlikely that they didn't validate their input and they should be outputting `bad request`, though (as in, *your* request is broken). – Tobia Tesan Sep 22 '15 at 18:09

0 Answers0