可以写java小程序来访问Servlet或者JSP
用到的核心类就是HttpURLConnection
Servlet 接受通过 HttpURLConnection 传递来的数据
public class HttpUrlConnectionServletr extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().write("abc");//接受过来的数据
String name=request.getParameter("name");//根据参数得到数据
String header=request.getHeader("a");
System.out.println(name);
System.out.println(header);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
Main方法中定义api
/**
* 读取服务器的数据
* @throws MalformedURLException
* @throws IOException
*/
private static void Test1() throws MalformedURLException, IOException {
URL url=new URL("http://localhost:8080/JspDemo/HttpUrlConnectionServletr");
HttpURLConnection con=(HttpURLConnection) url.openConnection();
InputStream inputStrea = con.getInputStream();//字节流
InputStreamReader inputStreamReader = new InputStreamReader(inputStrea);//转为字符流
//通过bufferReader 读取
BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
String content = bufferedReader.readLine();
int responseCode = con.getResponseCode();//获得状态码
String headerField=con.getHeaderField("Server");//获取消息头 名字为 Server的头
System.out.println(content);
System.out.println(responseCode);
System.out.println(headerField);
}
/**
* 给服务器传输数据
* @throws MalformedURLException
* @throws IOException
*/
private static void Test2() throws MalformedURLException, IOException {
URL url=new URL("http://localhost:8080/JspDemo/HttpUrlConnectionServletr");
HttpURLConnection con=(HttpURLConnection) url.openConnection();
con.setDoOutput(true);//cannot write to a URLConnection if doOutput=false - call setDoOutput(true)
//给服务器发送请求头
con.setRequestMethod("POST");
con.setRequestProperty("a", "tou");
OutputStream out = con.getOutputStream();
out.write("name=jibenmima".getBytes());
con.getResponseCode();//表示 请求完成 一个请求是有来回的
}
最近房子没网了,幸亏邻居家及时续上了 感谢~~~
网友评论