简体   繁体   English

将大量数据从 servlet 传输到 android 应用程序

[英]Transfer huge data from servlet to android application

I am developing an android application in which i have to store a bitmap in a remote server.我正在开发一个 android 应用程序,我必须在远程服务器中存储一个 bitmap 应用程序。 Steps are:步骤是:

Step 1: Convert the bitmap into byte array and send it from android application to server.I am sending the bitmap as MultipartEntity.In server side, i am receiving it in doPost() method.第 1 步:将 bitmap 转换为字节数组并将其从 android 应用程序发送到服务器。我将 bitmap 作为 MultipartEntity(在服务器端)发送。我在服务器端接收它。

Step 2: Store the byte array in mysql database.Bitmap is stored as blob data type.I am able to store the received byte array into mysql database.第2步:将字节数组存储在mysql数据库中。Bitmap存储为blob数据类型。我能够将接收到的字节数组存储到mysql数据库中。

Step 3: Retrieve the bitmap stored as blob and send it back to the android application.I am able to retrieve the blob and convert into byte array and send it.第 3 步:检索存储为 blob 的 bitmap 并将其发送回 android 应用程序。我能够检索 blob 并转换为字节数组并发送它。

My Issue我的问题

The problem is the data sent from server is received in small batches.The image length was 1380 but it is received in variable lengths of 10's,50's,100's.When i add up the total i am getting only 1345,missing few bytes of data.I am posting the code in receiving end.问题是从服务器发送的数据是小批量接收的。图像长度为 1380,但以 10's、50's、100's 的可变长度接收。当我将总数加起来时,我只得到 1345,缺少几个字节的数据.我在接收端发布代码。

URL url = new URL( "http://10.0.2.2:8080/ServerPartProject/BlobGetter");
 URLConnection yc = url.openConnection();              
 BufferedReader in = new BufferedReader(new       InputStreamReader(yc.getInputStream()));                                                      String data;
 int val=0; 
 while((data=in.readLine())!=null){
    val=val+data.length();  //The data.length is like 10,20..
 }
 System.out.println("Total value obtained is "+val);//val was 1345 where it should be 1380

sending end:发送端:

OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream());
writer.write(senddata);

How to receive it in full stretch?如何全面接收?

You can use JSON.您可以使用 JSON。

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    List<String> list = new ArrayList<String>();
    list.add("item1");
    list.add("item2");
    list.add("item3");
    String json = new Gson().toJson(list);

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

This will build and return the List in the following JSON format:这将以以下 JSON 格式构建并返回List

["item1","item2","item3"]

This is in turn parseable by org.json API in Android as follows:这又可由org.json中的 org.json API 解析,如下所示:

String jsonString = getServletResponseAsStringSomehow(); // HttpClient?
JSONArray jsonArray = new JSONArray(jsonString);
List<String> list = new ArrayList<String>();

for (int i = 0; i < jsonArray.length(); i++) {
    list.add(jsonArray.getString(i));
}

// Now you can use `list`.

Don't use readLine() .不要使用readLine() You are working with raw data.您正在处理原始数据。 Raw data does not have lines only text has.原始数据没有行,只有文本才有。

Some of your bytes are probably converted into 2 byte unicode characters which explains your perceived loss of data.您的某些字节可能已转换为 2 字节 unicode 字符,这解释了您感知到的数据丢失。

I would avoid using the character-oriented Reader and Writer to send and receive image data (which is presumably in binary [if you are base64 encoding or something, which you don't mention, disregard this]).我会避免使用面向字符的读取器和写入器来发送和接收图像数据(大概是二进制的[如果你是 base64 编码或其他东西,你没有提到,忽略这个])。 The bytes are being interpreted as characters, converted back to bytes, then interpreted as characters again, and finally back to bytes;字节被解释为字符,转换回字节,然后再次被解释为字符,最后返回字节; in the process the image data is being corrupted.在此过程中,图像数据被破坏。 Use the InputStream/OutputStream interfaces supplied by the Http objects instead of putting Readers and Writers on them.使用 Http 对象提供的 InputStream/OutputStream 接口,而不是在它们上面放置 Readers 和 Writers。

You are using readLine() for reading byte data, which is at least odd, if not the issue.您正在使用 readLine() 读取字节数据,如果不是问题的话,这至少很奇怪。 In your sample code, you are not closing your Readers (which should InputStreams).在您的示例代码中,您没有关闭您的阅读器(应该是 InputStreams)。 Buffered input may have some bytes left in the buffer which will not be read until flushed or closed.缓冲输入可能会在缓冲区中留下一些字节,这些字节在刷新或关闭之前不会被读取。

Hope this helps.希望这可以帮助。

If your database resides locally and not in the internet cloud, you can access it directly via JDBC API with JDBC connector mysql-connector-java-3.0.17-ga-bin.jar. If your database resides locally and not in the internet cloud, you can access it directly via JDBC API with JDBC connector mysql-connector-java-3.0.17-ga-bin.jar. Is not that you can't access your database remotely but is very unwise and risky to expose your database directly in the cloud.不是说您不能远程访问您的数据库,而是直接在云中公开您的数据库是非常不明智和冒险的。

For reading a blob to a bmp in Android, you can use BitmapFactory, like this:要在 Android 中将 blob 读取到 bmp,可以使用 BitmapFactory,如下所示:

// this is a snippet of course..

try
{
  Class.forName("com.mysql.jdbc.Driver");
  String astring = "jdbc:mysql://localhost:3306/mydb?user=root&password=pass"; 
  Connection ac = DriverManager. getConnection(astring);
  Statement st = ac.GetStatement();
  astring = "SELECT MYBLOB FROM MYTABLE";  // create your query here
  ResultSet rs = st.executeQuery(astring)

  if(rs.next())
  {
     java.sql.Blob ablob = rs.getBlob("MYBLOB");
     Bitmap bmp = BitmapFactory.decodeStream(ablob.getBinaryStream());

     // here you have your bmp, do whatever you want
     UseBmp(bmp);
  }

}
catch(Exception e)
{
  e.printStackTrace();
}

You'll need to implement a pool of connections to speed up query response times cause JDBC put a little overhead to Android when building a connection to server, it takes 2 to 3 seconds to start but once connected works very fast.您需要实现一个连接池来加快查询响应时间,因为 JDBC 在建立与服务器的连接时给 Android 带来了一点开销,启动需要 2 到 3 秒,但一旦连接工作速度非常快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM