2015-02-04 3 views
4

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

+1

충돌에 대한 오류 메시지는 무엇입니까? 문제는 당신이 HTTPS에 연결하고 있지 않지만 당신이'HttpsURLConnection'으로 형 변환하고 있다는 것입니다. – RealSkeptic

+0

예, 여기에 오류가 있습니다 "main"스레드의 예외 java.lang.ClassCastException : 변경하는 경우 sun.net.www.protocol.http.HttpURLConnection을 javax.net.ssl.HttpsURLConnection에 캐스팅 할 수 없습니다. –

+0

HTTPS에 더 이상 충돌하지 않지만 요청이 무기한 중단됩니다. –

답변

3

사용

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

당신은 HTTPS가 아닌 URL에 연결된다. obj.openConnection()에 전화하면 연결이 HTTP인지 HTTPS인지를 결정하고 적절한 개체를 반환합니다. http 일 경우 HttpsURLConnection을 반환하지 않으므로 변환 할 수 없습니다. HttpsURLconnection 때문에

는 모두 httphttps URL에 대한 작동 HttpURLConnection를 사용하여, HttpURLConnection 확장합니다. 코드에서 호출하는 메서드는 모두 HttpURLConnection 클래스에 있습니다.

+0

그걸 고정시켜 줘서 고마워! –