Nul*_*ion 8 php base64 android json blob
我有一个带MySQL的远程数据库,我将我的应用程序用户的照片存储在数据库中,作为LONGTEXT类型的数据库的一行.
我用Base64将照片转换为字符串.
我用JSON和PHP连接到我的远程数据库,因为这个,我必须使用Base64,因为据我所知,JSON和PHP需要在参数上发送字符串,而使用Base64我可以将照片转换为字符串.
它工作正常,但速度很慢.当我加载100 KB的照片时,需要花费很多时间,但是当我加载5 KB的照片时,它只需要两到三秒钟.
一位朋友告诉我使用BLOB而不是Base64,但是如何使用BLOB和JSON以及PHP连接到数据库?另外,我需要将图像存储在表格的一行上USER.这是因为用户没有将文件上传到远程服务器的权限,但他们可以通过将照片作为字符串添加到表格的一行来上传照片USER.
谢谢
编辑:
这是需要等待一段时间的代码(它在行中等待:while ((line = reader.readLine()) != null) {它正在等待reader.readLine() )
这段代码从远程数据库中获取一个用户,在我的应用程序上显示用户需要花费一些时间
public Friend RetrieveOneUser(String email)
{
Friend friend=null;
String result = "";
//the parameter data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email",email));
//http post
InputStream is=null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(this.BaseURL + this.GetOneUser_URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++)
{
JSONObject json_data = jArray.getJSONObject(i);
friend=new Friend(json_data.getString("email"),json_data.getString("password"), json_data.getString("fullName"), json_data.getString("mobilePhone"), json_data.getString("mobileOperatingSystem"),"",json_data.getString("photo"));
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return friend;
}
Run Code Online (Sandbox Code Playgroud)
将请求分为两部分:
我假设您有像http://example.com/userinfo/xxx这样的东西作为返回JSON的端点?添加像http://example.com/userinfo_image/xxx这样的端点只返回图像,然后您可以将其作为二进制块返回,而不是在JSON中将其编码为Base64.
这意味着您发出两个HTTP请求而不是一个,但根据应用程序的不同,您可以异步执行映像加载,如果是这样,通常可以从用户角度获得应用程序响应时间的大幅提升.
有关延迟加载图像的信息,请参阅Android开发者博客上的帖子以获取示例:
http://android-developers.blogspot.com/2010/07/multithreading-for-performance.html
如果您不能延迟加载图像,请考虑同时对图像和JSON执行并行请求.使用图像的二进制版本可以减少很少的网络带宽,并且一旦将数据传输到手机上,处理的处理就会少得多,它看起来仍然要快得多.