2012-03-26 84 views
1

我需要從android設備發送一些字節數組到Servlet。爲此,我嘗試使用下面的代碼:如何從Android設備發送字節數組到servlet

的Servlet:

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

    DataInputStream in = new DataInputStream((InputStream)request.getInputStream()); 
    response.setContentType("text/plain"); 
    byte[] buffer = new byte[1024]; 
    int len = 0; 
    File file; 
    file=new File(getServletContext().getRealPath("/POST_LOG!!!!.txt")); 
    if(!file.exists()){ 
     file.createNewFile(); 
    } 
    while ((len = in.read(buffer)) > 0) { 
      FileOutputStream fos = new FileOutputStream(getServletContext().getRealPath("/POST_LOG!!!!.txt"), true); 

      fos.write(buffer);    
      fos.close(); 
    } 

    PrintWriter out = response.getWriter(); 
    out.write("Done"); 
    out.close(); 

控制器側:

URL uploadUrl; 
    try { 
     uploadUrl = new URL(url); 
     HttpURLConnection c = (HttpURLConnection) uploadUrl 
       .openConnection(); 
     c.setRequestMethod("POST"); 

     c.setDoInput(true); 
     c.setDoOutput(true); 
     c.setUseCaches(false); 
     c.connect(); 
     OutputStream out = c.getOutputStream(); 

     for (int i = 0; i < 1000; i++) { // generate random bytes for 
              // uploading 
      byte[] buffer = new byte[256]; 
      for (int j = 0; j < 256; j++) { 
       Random r = new Random(); 
       buffer[j] = (byte) r.nextInt(); 
      } 

      out.write(buffer); 
      out.flush(); 
     } 

     out.close(); 

    } catch (Exception e) { 
     MessageBox("Error. " + e.toString()); 
    } 

    return (long) 0; 
} 

我不明白爲什麼這個代碼不工作。當我嘗試調試我的POST方法時,它甚至沒有調用。我會感激你的例子

+0

請分享servlet配置,URL映射和您使用來調用它servletn URL的你的web.xml條目。 – Santosh 2012-03-26 06:45:42

回答

2

我找到了解決辦法。我只是使用自定義InputStream更改了設備端代碼。

控制器側:

HttpPost httpPost = new HttpPost(url); 
    httpPost.setEntity(new InputStreamEntity(new MyInputStream(), 
      4096 * 1024 * 10)); 
    HttpResponse response = null; 

    try { 
     response = httpClient.execute(httpPost); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
     httpPost.abort(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
     httpPost.abort(); 
    } 
0

你有很多的選擇:

  • 發送字節值:125,11,25,40(這是一個愚蠢的選擇)
  • 發送base64-或十六進制 - 編碼,然後將其解碼(使用Apache公地編解碼器)
  • 提交爲multipart/form-data
相關問題