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

发布于 2024-11-19 14:41:55 字数 1153 浏览 2 评论 0原文

我正在开发一个 Android 应用程序,其中我必须在远程服务器中存储位图。 步骤是:

第 1 步: 将位图转换为字节数组并将其从 Android 应用程序发送到服务器。我将位图作为 MultipartEntity 发送。在服务器端,我在 doPost() 方法中接收它。

第2步:将字节数组存储在mysql数据库中。位图存储为blob数据类型。我能够将接收到的字节数组存储到mysql数据库中。

第3步:检索存储为blob的位图并将其发送回android应用程序。我能够检索blob并将其转换为字节数组并将其发送。

我的问题

问题是从服务器发送的数据是小批量接收的。图像长度是1380,但它是以10、50、100的可变长度接收的。当我将总数加起来时,我是仅得到 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

发送端:

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

如何全力接收?

I am developing an android application in which i have to store a bitmap in a remote server.
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.

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.

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.

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.

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

夏了南城 2024-11-26 14:41:55

不要使用 readLine()
您正在使用原始数据。原始数据没有行,只有文本有。

您的某些字节可能会转换为 2 字节 unicode 字符,这解释了您感知到的数据丢失。

Don't use 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.

荒芜了季节 2024-11-26 14:41:55

我会避免使用面向字符的 Reader 和 Writer 来发送和接收图像数据(大概是二进制的[如果你是 base64 编码或其他你没有提到的东西,请忽略这一点])。字节被解释为字符,转换回字节,然后再次解释为字符,最后返回字节;在此过程中图像数据被损坏。使用 Http 对象提供的 InputStream/OutputStream 接口,而不是在其上放置 Readers 和 Writers。

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]). 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.

过期情话 2024-11-26 14:41:55

您正在使用 readLine() 来读取字节数据,如果不是问题的话,这至少是奇怪的。在您的示例代码中,您没有关闭 Readers(应该是 InputStreams)。缓冲输入可能会在缓冲区中留下一些字节,这些字节在刷新或关闭之前不会被读取。

希望这有帮助。

You are using readLine() for reading byte data, which is at least odd, if not the issue. In your sample code, you are not closing your Readers (which should InputStreams). Buffered input may have some bytes left in the buffer which will not be read until flushed or closed.

Hope this helps.

北风几吹夏 2024-11-26 14:41:55

您可以使用 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);
}

这将以以下 JSON 格式构建并返回 List

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

这又可由 Android 中的 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`.

You can use 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:

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

This is in turn parseable by org.json API in Android as follows:

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`.
生死何惧 2024-11-26 14:41:55

如果您的数据库位于本地而不是互联网云中,您可以使用 JDBC 连接器 mysql-connector-java-3.0.17-ga-bin.jar 通过 JDBC API 直接访问它。并不是说您无法远程访问您的数据库,而是将您的数据库直接暴露在云中是非常不明智和危险的。

为了在 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();
}

您需要实现一个连接池来加快查询响应时间,因为 JDBC 在构建与服务器的连接时会给 Android 带来一些开销,它启动需要 2 到 3 秒,但连接后工作速度非常快。

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:

// 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文