我基本上实现了一个向servlet发送HTTP请求的java控制台程序。此代码运行但不提供任何输出。我这里有两个问题 -
在url.openConnection()之后,我看到了' connected' httpConn对象中的字段,它表示false。但如果我删除此评论
//int responsecode = httpConn.getResponseCode();
返回状态代码200(成功)。这是什么意思?连接是否已建立?当我telnet - o localhost 8080它说'按任意键继续'当我这样做时,它说'与主机失去联系'此外,当执行上面的代码时,控制台显示此
null
null
Servlet Reached
我得到以下异常(在整个程序以调试模式运行之后)
java.net.ProtocolException: Cannot write output after reading input.
当我完成下一行代码(调试模式)时
StringBuffer requestParams = new StringBuffer();
控制台不再显示输出。究竟发生了什么?
另一个问题 - 现在我在HTTP POST消息中发送字符串作为参数但是如何发送整个对象?我必须使用序列化吗?任何帮助将非常感激。
package tutorial;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.net.*;
import java.util.Iterator;
class HttpUtility{
private static HttpURLConnection httpConn;
public static HttpURLConnection sendPostRequest(String requestURL,
ArrayList list) throws IOException {
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
//int responsecode = httpConn.getResponseCode();
//httpConn.setDoInput(true); // true indicates the server returns response
StringBuffer requestParams = new StringBuffer();
if (list != null && list.size() > 0) {
httpConn.setDoOutput(true); // true indicates POST request
// creates the list string, encode them using URLEncoder
Iterator iter = list.iterator();
int index=0;
while (iter.hasNext()) {
String lValue = (String) iter.next();
requestParams.append(URLEncoder.encode("params"+ index++, "UTF-8"));
requestParams.append("=").append(
URLEncoder.encode(lValue, "UTF-8"));
requestParams.append("&");
}
System.out.println(requestParams.toString());
String requestParam = requestParams.toString();
DataOutputStream wr = new DataOutputStream(httpConn.getOutputStream());
wr.writeBytes(requestParam);
wr.flush();
wr.close();
/*
OutputStream ops = httpConn.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(ops);
writer.write(requestParams.toString());
writer.flush();
*/
/*
OutputStream os = httpConn.getOutputStream();
os.write(requestParam.getBytes());
os.flush();
os.close();
*/
}
return httpConn;
}
public static void disconnect() {
if (httpConn != null) {
httpConn.disconnect();
}
}
}
class ConsoleHttpRequest {
public static String requestURL;
public static void main(String[] args) {
ArrayList list = new ArrayList();
requestURL = "http://localhost:8080/ServletTutorial/ConsoleToServlet"; // No Exception but no connection
//requestURL = "https://localhost:8080/ServletTutorial/ConsoleToServlet"; //javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
//requestURL = "http://localhost"; // java.net.ConnectException: Connection refused: connect
//requestURL="https://10.167.7.178"; // java.net.ConnectException: Connection refused: connect
//requestURL="http://www.google.com"; // No Exception but no connection as well
list.add("Welcome");
list.add("to");
list.add("the");
list.add("World");
list.add("of");
list.add("Java");
list.add("Programming");
try {
HttpUtility.sendPostRequest(requestURL, list);
} catch (IOException ex) {
ex.printStackTrace();
}
HttpUtility.disconnect();
}
}
这是从控制台程序接收请求并在控制台中打印的servlet。
package tutorial;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ConsoleToServlet
*/
public class ConsoleToServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String s=request.getParameter("params1");
System.out.println(s);
System.out.println("Servlet Reached");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String s=request.getParameter("params1");
System.out.println(s);
doPost(request,response);
}
}
答案 0 :(得分:1)
为什么在“url.openConnection(...)”之后得到'false'值
用debugtool和tcpdump **(sudo tcpdump -s 0 -A port 80)**检查后, 我发现在调用openConnection时没有发送http请求头,刚开始读取输入流后,将发送来自客户端的http请求。
关于ProtocolException
如果你调用“httpConn.getResponseCode()”,则表示http响应头被发送到客户端,因此你不能发送http请求(除非你使用http协议的“管道”功能,但它必须是服务器端也支持)
发送整个对象
试试吧:
HttpURLConnection httpConn =(HttpURLConnection) url.openConnection();
httpConn.setDoOutput(true);
ObjectOutputStream objOts=new ObjectOutputStream(httpConn.getOutputStream());
objOts.writeObject(new Object());
objOts.close();