簡體   English   中英

將byte []從獨立的main發送到servlet

[英]Send byte[] from standalone main to a servlet

如何從測試客戶端(獨立)向Servlet發送byte[]

這是我的代碼:

public class Sent
{
    public static void main(String[] args) throws Exception
    {
        URL url = new URL("http://mydomain.com:8080/demo/myServlet");
        HttpURLConnection oc = (HttpURLConnection)url.openConnection(); 

        oc.setDoOutput(true);
        oc.setUseCaches(false);

        OutputStream os = oc.getOutputStream();     
        os.write("Hello world".getBytes());
        os.flush();     
        os.close();
    }
}

這是我的servlet:

@WebServlet("/myServlet")
public class MyServlet extends HttpServlet
{
    private static final long serialVersionUID=1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException
    {
        ServletInputStream sis = request.getInputStream();
        int c;
        while( (c=sis.read())>=0 )
        {
            System.out.println((char)c);
        }

        sis.close();
    }
}

使用此代碼,servlet不會執行任何操作。 沒什么,我的意思是,它不會在控制台上寫任何東西。

謝謝。

你打電話時

oc.setDoOutput(true);

HttpURLConnection假定您正在嘗試發送POST請求。 您沒有POST請求處理程序,即。 沒有doPost() ,因此您繼承了HttpServlet的實現,該實現返回405 Method Not Allowed響應。 您會看到,如果您做了

System.out.println(oc.getResponseCode());

而是將doGet更改為doPost 或兩者兼而有之,由您決定。

暫無
暫無

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

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