我正在使用凌空下载文件但我无法打开它,它显示了这一点:
无法显示PDF(name.pdf格式无效)
还要提一下,服务返回11kb byte []并进行调试,我收到了16kb的响应。我正在使用的代码是:
InputStreamVolleyRequest request = new InputStreamVolleyRequest(Request.Method.POST, uri,
new Response.Listener<byte[]>() {
@Override
public void onResponse(byte[] response) {
try {
if (response!=null) {
if(Build.VERSION.SDK_INT>22){
requestPermissions(new String[] {"android.permission.WRITE_EXTERNAL_STORAGE","android.permission.READ_EXTERNAL_STORAGE"}, 1);
}
File baseDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
baseDir.mkdirs();
File carpeta = new File(baseDir + nombre_carpeta);
carpeta.mkdirs();
File file = new File(baseDir, documento.NombreFichero.replace("\\","/"));
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
bos.write(response);
bos.flush();
bos.close();
Log.d("NEWFILE", file.getAbsolutePath());
Toast.makeText(getActivity(), "Descarga completa.", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
Log.d("KEY_ERROR", "UNABLE TO DOWNLOAD FILE");
e.printStackTrace();
}
}
} ,new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}, (HashMap<String, String>) params);
RequestQueue mRequestQueue = Volley.newRequestQueue(getActivity().getApplicationContext(), new HurlStack());
mRequestQueue.add(request);
提前致谢!
答案 0 :(得分:1)
最后,我将响应发送为字符串,然后使用 android.util.Base64 对其进行解码。这是代码:
StringRequest sr = new StringRequest(Request.Method.POST, uri, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try{
File baseDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
baseDir.mkdirs();
File carpeta = new File(baseDir + nombre_carpeta);
carpeta.mkdirs();
File file = new File(baseDir, documento.NombreFichero.replace("\\","/"));
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(file));
FileOutputStream fos = new FileOutputStream(file);
byte[] respuesta = android.util.Base64.decode(response.getBytes(), android.util.Base64.DEFAULT);
fos.write(respuesta);
fos.flush();
fos.close();
output.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
答案 1 :(得分:0)
这不是编程问题。我建议您在模拟器或设备中安装pdf阅读器(Google PDF Viewer)。
如果您使用的是模拟器,则可能需要使用已安装Google Play的版本。然后你可以安装pdf阅读器。