1. 程式人生 > >main函式載入jetty,及java請求url

main函式載入jetty,及java請求url

建立servlet處理請求
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    InputStream s=request.getInputStream();
    String a="";
    BufferedReader reader=new BufferedReader(new InputStreamReader(s));
    String str;
    while ((str = reader.readLine()) != null){
        System.out.println(str);
        a=str;
    }
    reader.close();
    response.getWriter().write(a);
}
客戶端程式碼
public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
    String host="http://localhost:8080/test/hello";
    HttpURLConnection conn;
    try {
        URL url=new URL(host);
        conn = (HttpURLConnection)url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(true);
        conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        conn.connect();
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        String hello=URLEncoder.encode("hello", "utf-8");
        out.writeBytes(hello);
        out.flush();
        out.close(); 
        InputStream in=conn.getInputStream();
        BufferedReader reader=new BufferedReader(new InputStreamReader(in));
        String str;
        while ((str = reader.readLine()) != null){
            System.out.println(str);
        }
        reader.close();
        conn.disconnect();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

載入jetty及webxml設定埠
public static void main(String[] args) {
// TODO Auto-generated method stub
Server server=new Server(8080);
WebAppContext context = new WebAppContext();
context.setDescriptor(“E:/work/test/src/main/webapp/WEB-INF/web.xml”);
context.setResourceBase(“E:/work/test/src/main/webapp”);
context.setContextPath(“/test”);
context.setParentLoaderPriority(true);
server.setHandler(context);
try {
server.start();
server.join();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}