求一个简单的JAVA里用HttpURLconnetcion连接Servelt的例子

2024-12-25 12:55:52
推荐回答(1个)
回答1:

Service 的部份 import java.io.IOException;
import java.io.InputStream;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestServlet extends HttpServlet { @Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().println("AAA");
InputStream in = request.getInputStream();
byte[] b = new byte[1024];
in.read(b);
System.out.println(new String(b).trim());
in.close();
}
}
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL; Client的部分public class Test {
public static void main(String[] args) throws Exception {
URL url = new URL(" http://127.0.0.1:8080/security2/ac.do");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
OutputStream out = con.getOutputStream();
out.write("发送".getBytes());
out.close();

InputStream in = con.getInputStream();
byte[] b = new byte[in.available()];
in.read(b);
System.out.println(new String(b));
in.close();

}
}
web.xml配置
xmlns=" http://java.sun.com/xml/ns/javaee"
xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

ac
TestServlet


ac
/ac.do