POST 요청을 처리 할 수있는 간단한 HTTP 서버를 Java로 작성하려고합니다. 내 서버가 GET을 성공적으로 수신하는 동안 POST에서 충돌합니다. 여기 POST 요청을 처리하는 Java HTTP 서버
서버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
// 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());
}
각각의 시간을 보낼 때 사용하는 자바 코드이 줄
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
에 POST 요청 충돌 하지만 내가 찾은 예제에서 제공된 URL로 URL을 변경하면 작동합니다. 대신
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
의
충돌에 대한 오류 메시지는 무엇입니까? 문제는 당신이 HTTPS에 연결하고 있지 않지만 당신이'HttpsURLConnection'으로 형 변환하고 있다는 것입니다. – RealSkeptic
예, 여기에 오류가 있습니다 "main"스레드의 예외 java.lang.ClassCastException : 변경하는 경우 sun.net.www.protocol.http.HttpURLConnection을 javax.net.ssl.HttpsURLConnection에 캐스팅 할 수 없습니다. –
HTTPS에 더 이상 충돌하지 않지만 요청이 무기한 중단됩니다. –