簡體   English   中英

希望與Servlet交互的Java控制台程序

[英]Java Console program wanting to interact with the Servlet

我基本上正在實現一個Java控制台程序,該程序將HTTP請求發送到Servlet。 此代碼運行,但沒有任何輸出。 我在這里有兩個問題-

在url.openConnection()之后,我看到了httpConn對象中“ connected”字段的值,它說是false。 但是,如果我刪除此評論

    //int responsecode = httpConn.getResponseCode();   

返回狀態碼200(成功)。 這是什么意思? 是否建立連接? 當我進行telnet-本地主機8080時,它說“按任意鍵繼續”,當我這樣做時,它說“與主機的連接丟失”。此外,執行上述代碼后,控制台將顯示此信息。

null
null
Servlet Reached

我在下面得到了異常(整個程序在調試模式下運行之后)

java.net.ProtocolException: Cannot write output after reading input.

當我完成執行下一行代碼時(調試模式)

StringBuffer requestParams = new StringBuffer();

控制台不再顯示輸出。 到底是什么情況?

另一個問題-現在,我要在HTTP POST消息中將字符串作為參數發送,但是如何發送整個對象? 我必須使用序列化嗎? 任何幫助將不勝感激。

package tutorial;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.net.*;
import java.util.Iterator;

class HttpUtility{

    private static HttpURLConnection httpConn;

    public static HttpURLConnection sendPostRequest(String requestURL,
            ArrayList list) throws IOException {

        URL url = new URL(requestURL);
        httpConn = (HttpURLConnection) url.openConnection();

        //int responsecode = httpConn.getResponseCode();       
        //httpConn.setDoInput(true); // true indicates the server returns response

        StringBuffer requestParams = new StringBuffer();

        if (list != null && list.size() > 0) {

            httpConn.setDoOutput(true); // true indicates POST request
            // creates the list string, encode them using URLEncoder
            Iterator iter = list.iterator();
            int index=0;

            while (iter.hasNext()) {
                String lValue = (String) iter.next();
                requestParams.append(URLEncoder.encode("params"+ index++, "UTF-8"));
                requestParams.append("=").append(
                        URLEncoder.encode(lValue, "UTF-8"));
                requestParams.append("&");
            }

            System.out.println(requestParams.toString());
            String requestParam = requestParams.toString();

            DataOutputStream wr = new DataOutputStream(httpConn.getOutputStream());
            wr.writeBytes(requestParam);
            wr.flush();
            wr.close();

            /*
            OutputStream ops = httpConn.getOutputStream();
            OutputStreamWriter writer = new OutputStreamWriter(ops);           
            writer.write(requestParams.toString());
            writer.flush();
            */

            /*
            OutputStream os = httpConn.getOutputStream();
            os.write(requestParam.getBytes());
            os.flush();
            os.close();
            */
        }

        return httpConn;
    }

    public static void disconnect() {
        if (httpConn != null) {
            httpConn.disconnect();
        }
    }
}


class ConsoleHttpRequest {

    public static String requestURL;

    public static void main(String[] args) {    

        ArrayList list = new ArrayList();

        requestURL = "http://localhost:8080/ServletTutorial/ConsoleToServlet"; // No Exception but no connection
        //requestURL = "https://localhost:8080/ServletTutorial/ConsoleToServlet"; //javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
        //requestURL = "http://localhost"; // java.net.ConnectException: Connection refused: connect
        //requestURL="https://10.167.7.178"; // java.net.ConnectException: Connection refused: connect
        //requestURL="http://www.google.com"; // No Exception but no connection as well     

        list.add("Welcome");
        list.add("to");
        list.add("the");
        list.add("World");
        list.add("of");
        list.add("Java");
        list.add("Programming");

        try {
            HttpUtility.sendPostRequest(requestURL, list);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        HttpUtility.disconnect();
    }
}

這是從控制台程序接收請求並在控制台中簡單打印的servlet。

package tutorial;

    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    /**
     * Servlet implementation class ConsoleToServlet
     */
    public class ConsoleToServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;

        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            String s=request.getParameter("params1");
            System.out.println(s);
            System.out.println("Servlet Reached");
        }

        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            String s=request.getParameter("params1");
            System.out.println(s);
            doPost(request,response);
        }

    }

為什么在“ url.openConnection(...)”之后得到“假”值

使用debugtool和tcpdump **(sudo tcpdump -s 0 -A port 80)**檢查后,我發現調用openConnection時未發送http請求標頭,就在您開始閱讀inputstream后,來自客戶端的http請求將被發送。

關於ProtocolException

如果調用“ httpConn.getResponseCode()”,則表示已將http響應標頭發送到客戶端,因此無法發送http請求(除非您使用http協議的“管道”功能,但服務器必須支持它)一邊也)

發送整個對象
試試吧 :

    HttpURLConnection httpConn =(HttpURLConnection) url.openConnection();       
    httpConn.setDoOutput(true);
    ObjectOutputStream objOts=new ObjectOutputStream(httpConn.getOutputStream());
    objOts.writeObject(new Object());
    objOts.close();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM