Java HttpURLConnection 小demo

可以寫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ù)上了 感謝~~~

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容