簡體   English   中英

Java httpserver在收到POST請求時崩潰

[英]Java httpserver crashes upon receiving POST requests

我正在嘗試用Java編寫一個可以處理POST請求的簡單HTTP服務器。 當我的服務器成功收到GET時,它會在POST上崩潰。

這是服務器

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

這是我用來發送POST的Java代碼

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

每次POST請求在此行崩潰

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

但是,當我將URL更改為示例中提供的URL時,我發現它可以正常工作。

代替

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

使用

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

您正在連接到非HTTPS的URL。 當您調用obj.openConnection() ,它會確定連接是HTTP還是HTTPS,並返回相應的對象。 當它是http ,它不會返回HttpsURLConnection ,因此您無法轉換為它。

但是,由於HttpsURLconnection擴展了HttpURLConnection ,因此使用HttpURLConnection將同時適用於httphttps URL。 您在代碼中調用的方法都存在於HttpURLConnection類中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM