Java httpserver crashes upon receiving POST requests
Asked Answered
S

1

6

I am trying to write a simple HTTP server in Java that can handle POST requests. While my server successfully receives the GET, it crashes on the POST.

Here is the server

public class RequestHandler {
    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
        server.createContext("/requests", new MyHandler());
        server.setExecutor(null); // creates a default executor
        server.start();
    }

    static class MyHandler implements HttpHandler {
        public void handle(HttpExchange t) throws IOException {
            String response = "hello world";
            t.sendResponseHeaders(200, response.length());
            System.out.println(response);
            OutputStream os = t.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }
    }
}

And here is the Java code I use to send the POST

// HTTP POST request
private void sendPost() throws Exception {

    String url = "http://localhost:8080/requests";
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

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

    String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

    // Send post request
    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();

    //print result
    System.out.println(response.toString());
}

Each time the POST request crashes on this line

HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

but when I change the URL to the one provided in the example where I found this it works.

Salver answered 4/2, 2015 at 15:34 Comment(4)
And what is the error message on the crash? I would suspect the problem is that you are not connecting in HTTPS but you are casting to HttpsURLConnection.Damiano
yes I believe so, here is the error Exception in thread "main" java.lang.ClassCastException: sun.net.www.protocol.http.HttpURLConnection cannot be cast to javax.net.ssl.HttpsURLConnectionSalver
if I change it to HTTPS it no longer crashes but the request hangs indefinitely, any suggestions?Salver
Yes, read the input stream in your server. Your request is trying to write but there is nobody on the other end that reads it.Damiano
D
4

Instead of

HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

Use

HttpURLConnection con = (HttpURLConnection) obj.openConnection();

You are connecting to a URL which is not HTTPS. When you call obj.openConnection(), it decides whether the connection is HTTP or HTTPS, and returns the appropriate object. When it's http, it won't return an HttpsURLConnection, so you cannot convert to it.

However, since HttpsURLconnection extends HttpURLConnection, using HttpURLConnection will work for both http and https URLs. The methods that you are calling in your code all exist int the HttpURLConnection class.

Damiano answered 4/2, 2015 at 15:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.