java - 如何将字节数组从 Android 设备发送到 servlet

标签 java android servlets

我需要从 Android 设备向 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 方法时,它甚至没有被调用。我将感谢你的例子

最佳答案

我找到了解决方案。我刚刚使用自定义 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();
    }

关于java - 如何将字节数组从 Android 设备发送到 servlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9867626/

相关文章:

java - 如何传递 `Class<T>` 的 `List<MyDevice>` ?

java - Runtime.getRuntime() 不在服务器中提供输出

Android 资源 $NotFoundException 计算表达式时 - Kotlin

java - cron4j descheduling servlet/actionbean 上的任务

java - 处理 3 - 使用 noFill() 后填充形状

java - 如何在jsp中显示3个数组列表?

android - Firestore 任务 whenallcomplete() - 任务尚未完成

Android AsyncTask 卡住 UI

java - JSP:在文件上传时获取 MIME 类型

Java Servlet 从一个 Servlet 重定向到另一个 Servlet,然后返回到初始 Servlet