可以寫java小程序來(lái)訪問Servlet或者JSP
用到的核心類就是HttpURLConnection
Servlet 接受通過 HttpURLConnection 傳遞來(lái)的數(shù)據(jù)
public class HttpUrlConnectionServletr extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().write("abc");//接受過來(lái)的數(shù)據(jù)
String name=request.getParameter("name");//根據(jù)參數(shù)得到數(shù)據(jù)
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
/**
* 讀取服務(wù)器的數(shù)據(jù)
* @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();//字節(jié)流
InputStreamReader inputStreamReader = new InputStreamReader(inputStrea);//轉(zhuǎn)為字符流
//通過bufferReader 讀取
BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
String content = bufferedReader.readLine();
int responseCode = con.getResponseCode();//獲得狀態(tài)碼
String headerField=con.getHeaderField("Server");//獲取消息頭 名字為 Server的頭
System.out.println(content);
System.out.println(responseCode);
System.out.println(headerField);
}
/**
* 給服務(wù)器傳輸數(shù)據(jù)
* @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)
//給服務(wù)器發(fā)送請(qǐng)求頭
con.setRequestMethod("POST");
con.setRequestProperty("a", "tou");
OutputStream out = con.getOutputStream();
out.write("name=jibenmima".getBytes());
con.getResponseCode();//表示 請(qǐng)求完成 一個(gè)請(qǐng)求是有來(lái)回的
}
最近房子沒網(wǎng)了,幸虧鄰居家及時(shí)續(xù)上了 感謝~~~