Android的使用JSON发送请求并得到Java的响应Android、JSON、Java

2023-09-04 23:33:26 作者:所谓的无所谓

可能重复:   在安卓使用JSON发送请求

Possible Duplicate: send request using json in android

您好,

我是新手Android开发,我使用JSON发送和从服务器获取数据。但我用了Android和服务器之间的文字工作。现在,我想从Android的从服务器数据库中发送图像数据到服务器,反之亦然,获取图像数据到Android。谁能告诉我我怎么能做到这一点?

I am newbie Android developer, I am using JSON to send and retrieve data from server. But I used to work with text between Android and server. Now I would like to send image data from Android to server and vice versa, retrieve image data from server database to Android . Can anyone show me how I can accomplish this?

感谢

推荐答案

我假设你已经实现了HTTP的JSON调用。

I am assuming that you have already implemented the JSON calls over HTTP.

您需要将图像转换为Base64的EN codeD字符串在发送到服务器。基于64位功能是从Android 2.2的android的UTIL库的一部分。如果您打算支持早期版本中,你可以从Android源代码的源$ C ​​$ C。这里的地点。它没有依赖关系涉及一个独立的文件。

You need to convert the Image to a Base64 encoded string while sending to the server. The Base64 functions are part of the android util library from Android 2.2. If you plan to support earlier versions you can get the source code from the Android source tree. Here's the location. It's a standalone file with no dependencies involved.

尝试使用的图像文件进行编码/解码如果可能的话,而不是位图,因为这有助于避免内存错误出在与大型图像处理。 下面是code的编码功能。

Try to use the image file for encoding/decoding if possible instead of the bitmap as this helps in avoiding out of memory errors when dealing with large images. Here's code for the encoding function.

private String getBase64String(String sFileName){


    File imagefile = new File(sFileName); 
    byte[] data = new byte[(int) imagefile.length()];

    FileInputStream fis;
    try {
        fis = new FileInputStream(imagefile);

        fis.read(data);
        fis.close();
        return  Base64.encodeToString(data,0);
    } catch (Exception e) {

        return "";
    }
}