1

I'm implementing some simple java class in order to send an HTTP Request with POST method and also another java class in order to receive it.
The server works fine when I make a POST request by means of my browser(Chrome), or an application(I have used Postman in this case) but it ends up with problem when I send HTTP Request with java!

My sending HTTP class is "Sender.java", containing the following snippet:

String url = "http://localhost:8082/";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();

// Setting basic post request
con.setRequestMethod("POST");       
//con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
//con.setRequestProperty("Content-Type","text/plain");

// Send post request
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write("Just Some Text".getBytes("UTF-8"));
os.flush();
os.close();
//connect to the Server(resides at Server.java)
con.connect();

I have commented some lines of code setting Headers like "Accept-Language" and "Content-Type" because I don't know whether or not are these headers required for the java program to work out?

The server is another java program named "Server.java". Here is the snippet related to reading HTTP Request made by the Sender.java(if need be).

int servPort = 8082;
// Create a server socket to accept HTTP client connection requests
HttpServer server = HttpServer.create(new InetSocketAddress(servPort), 0);
System.out.println("server started at " + servPort);

server.createContext("/", new PostHandler());//PostHandler implements HttpHandler
server.setExecutor(null);

server.start();

All I want is to send a plaintext as the body of my HTTP Request with the Post method. I have read plenty of sites and even related questions at this site. But it still doesn't work out. In other words, whenever I create an HTTP Request from "Sender.java", nothing appears at "Server.java". I just want to know what's wrong with my snippets and how should I fix that?

Agent47
  • 111
  • 8
  • What error do you get in Java? Is it simply not received? What actually happens? – basic Oct 24 '18 at 17:45
  • Have you used a network analysis tool such as Wireshark to see what (if anything) is actually being sent across the sockets? – Joe C Oct 24 '18 at 17:47
  • There is no Error. The problem is nothing happens! I expect the HTTP Post to be sent by Sender.java and read by Server.java, as in the case of my browser or Postman. – Agent47 Oct 24 '18 at 17:49
  • @JoeC let's check that. – Agent47 Oct 24 '18 at 18:10

4 Answers4

2

I tested this and it's working:

//Sender.java
String url = "http://localhost:8082/";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();


con.setRequestMethod("POST");       
con.setDoOutput(true);

OutputStream os = con.getOutputStream();
os.write("Just Some Text".getBytes("UTF-8"));
os.flush();

int httpResult = con.getResponseCode(); 
con.disconnect();

As you can see, connect is not necessary. The key line is

int httpResult = con.getResponseCode();

1

When you send a POST form using the browser, it sends the form in a certain format, defined in RFC1866, you have to recreate this on Java when making a post request.

With this format, its important you set the Content-Type header to application/x-www-form-urlencoded, and pass the body as you would do in a url with a get request.

Borrowing some code of my previous answer to POST in Java:

URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();

// Setting basic post request
con.setRequestMethod("POST");    

Map<String,String> form = new HashMap<>();

// Define the fields
form.put("username", "root");
form.put("password", "sjh76HSn!"); // This is a fake password obviously

// Build the body
StringJoiner sj = new StringJoiner("&");
for(Map.Entry<String,String> entry : arguments.entrySet())
    sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" 
         + URLEncoder.encode(entry.getValue(), "UTF-8"));
byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8);
int length = out.length;

// Prepare our `con` object
con.setFixedLengthStreamingMode(length);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.connect();
try (OutputStream os = con.getOutputStream()) {
    os.write(out);
}
Ferrybig
  • 15,951
  • 6
  • 51
  • 69
  • This is the answer! Fixed my issues. Thank you. It's very important to encode the post body correctly. – parsecer Dec 06 '19 at 05:58
0

Maybe “localhost” in the sender url does not resolve to the same ip that the server binds to? Try changing to 127.0.0.1 or your actual IP address.

FelixHJ
  • 945
  • 3
  • 10
  • 24
  • hmm is it the exact same URL and/or IP in Sender.java as it is in POSTMAN/Chrome? – FelixHJ Oct 25 '18 at 07:58
  • 1
    Yes. The exact URL and exact Port. The problem was entitled by not invoking the getResponseCode() : "int httpResult = con.getResponseCode();". I don't know why but It worked when I added this line, due to what aka-one said – Agent47 Oct 25 '18 at 17:42
0

try with PrintStream

        String url = "http://localhost:8082/";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // Setting basic post request
        con.setRequestMethod("POST");       
        //con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        //con.setRequestProperty("Content-Type","text/plain");

        // Send post request
        con.setDoOutput(true);
        OutputStream os = con.getOutputStream();
        java.io.PrintStream printStream = new java.io.PrintStream(os);
        printStream.println("Just Some Text");
        con.getInputStream();//Send request
        os.flush();
        os.close();
Gnk
  • 585
  • 3
  • 10