我试图用Java编写一个简单的HTTP服务器,它可以处理POST请求。虽然我的服务器成功接收的GET,它崩溃的讯息。
这里是服务器
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在我发现这它的工作原理所提供的示例之一。
代替
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
采用
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
您要连接到这不是一个HTTPS URL。当你调用obj.openConnection()
,它决定连接是HTTP或HTTPS,并返回相应的对象。当它的http
,它不会返回HttpsURLConnection
,所以你不能转换到它。
然而,由于HttpsURLconnection
延伸HttpURLConnection
,使用HttpURLConnection
将两个http
和https
网址。你是在你的代码中调用的所有方法中存在的int HttpURLConnection
类。