Ale*_*ear 6 java post httpserver
我正在尝试用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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我用来发送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());
}
Run Code Online (Sandbox Code Playgroud)
每次POST请求在此行崩溃
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
Run Code Online (Sandbox Code Playgroud)
但是,当我将URL更改为示例中提供的URL时,我发现它可以正常工作.
代替
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
Run Code Online (Sandbox Code Playgroud)
使用
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
Run Code Online (Sandbox Code Playgroud)
您正在连接到非 HTTPS 的 URL。当您调用 时obj.openConnection(),它会决定连接是 HTTP 还是 HTTPS,并返回适当的对象。当它是 时http,它不会返回HttpsURLConnection,因此您无法转换为它。
然而,由于HttpsURLconnectionextends HttpURLConnection, usingHttpURLConnection将适用于http和httpsURL。您在代码中调用的方法都存在于类中HttpURLConnection。
| 归档时间: |
|
| 查看次数: |
21238 次 |
| 最近记录: |