我有一个在线servlet,我正在尝试联系以进行一些基本的测试.这是servlet代码:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class index extends HttpServlet {
private static final long serialVersionUID = 1L;
public index() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
long time1 = System.currentTimeMillis();
long time2 = time1 + 10000;
out.println(time1);
long i = 400000000l;
while (System.currentTimeMillis() < time2) {
i++;
}
out.print(time2);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我正在尝试使用以下代码从服务器获取信息:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpRequest {
public static void main(String args[]) {
BufferedReader rd;
OutputStreamWriter wr;
try {
URL url = new URL("http://blahblahblah/index");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
wr = new OutputStreamWriter(conn.getOutputStream());
wr.flush();
conn.setConnectTimeout(50000);
rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是我一直得到同样的405错误.我究竟做错了什么?
您所看到的是HttpServlet默认实现doPost(),因为您override在indexservlet中没有它.
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_post_not_supported");
if (protocol.endsWith("1.1")) {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
} else {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
}
}
Run Code Online (Sandbox Code Playgroud)
它会立即发送405响应.
这是因为你打电话
conn.getOutputStream()
Run Code Online (Sandbox Code Playgroud)
这使URLConnection你认为你POST默认发送一个,而不是GET你期望的.你甚至没有使用OutputStream那么为什么打开它,那么flush()它再也不是我们了?
wr = new OutputStreamWriter(conn.getOutputStream());
wr.flush();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13479 次 |
| 最近记录: |