Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/actionscript-3/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android-我从服务器上获得了PDF(或)JPG(或)PNG文件形式的Json响应。如何处理它供用户查看(或)下载_Android_Json_Pdf_Jsonresult_Jsonresponse - Fatal编程技术网

Android-我从服务器上获得了PDF(或)JPG(或)PNG文件形式的Json响应。如何处理它供用户查看(或)下载

Android-我从服务器上获得了PDF(或)JPG(或)PNG文件形式的Json响应。如何处理它供用户查看(或)下载,android,json,pdf,jsonresult,jsonresponse,Android,Json,Pdf,Jsonresult,Jsonresponse,我正在使用 http连接方法:获取 请求/响应:JSON 我有一些带有ID的记录(参见下图)。当用户单击记录时。我正在使用单击的记录ID调用HttpConnection(JSON请求)到服务器 Json请求URL:http://xyz.in/api/mobile/document/12345/{记录Id} 在这里,我从服务器获得了PDF(或)JPG(或)PNG格式的Json响应 Json响应: %PDF-1.5 %���� 1 0 obj <</Type/Catalog/Pag

我正在使用

http连接方法:获取

请求/响应:JSON

我有一些带有ID的记录(参见下图)。当用户单击记录时。我正在使用单击的记录ID调用HttpConnection(JSON请求)到服务器

Json请求URL:
http://xyz.in/api/mobile/document/12345/{记录Id}

在这里,我从服务器获得了PDF(或)JPG(或)PNG格式的Json响应

Json响应:

%PDF-1.5

%����

1 0 obj

<</Type/Catalog/Pages 2 0 R/Lang(en-US) /StructTreeRoot 51 0 R/MarkInfo<</Marked true>>>>

endobj

2 0 obj

<</Type/Pages/Count 11/Kids[ 3 0 R 10 0 R 18 0 R 21 0 R 24 0 R 27 0 R 30 0 R 33 0 R 36 0 R 39 0 R 47 0 R] >>

endobj

3 0 obj

<</Type/Page/Parent 2 0 R/Resources<</ExtGState<</GS5 5 0 R/GS6 6 0 R>>/Font<</F1 7 0 R>>/XObject<</Image9 9 0 R>>/ProcSet[/PDF/Text/ImageB/ImageC/ImageI] >>/MediaBox[ 0 0 960 540] /Contents 4 0 R/Group<</Type/Group/S/Transparency/CS/DeviceRGB>>/Tabs/S/StructParents 0>>

endobj

4 0 obj

<</Filter/FlateDecode/Length 340>>

stream

x���Mk1����9�
fg&������ҥ=��U)T����MV[?.�fC��ɛY(��j���nC�ׅ)P!"1���!X���J�؀������S
���at����5�����.���$Tl)��˸6�����J��u:j�{µyGa�4�iuW�Gj0I?�U��u
�S��k4Z��N�7�T�T�Y��)�QY�b&�@��l��Ͼsr�{��R��?Cu+E�����g���9|�(͊Ϣ��r�­�)�e��5���R�N䬳q��oϥ�m6ټ����<��<47�=��sH�?��e�v��+����K�.���|ZBo��߶�

endstream

endobj
%PDF-1.5
%����
10 obj
endobj
20 obj
endobj
30 obj
endobj
40 obj
流动
x���Mk1����9�
前景&������ҥ=��U) T����MV[?。�足球俱乐部��ɛY(��J���数控�ׅ)P!“1���!X���J�؀������s
���在����5.�����.���$(Tl)��˸6�����J��u:j�{µyGa�4.�iuW�Gj0I?�U��U

�s��k4Z��N�7.�T�T�Y��)�QY�b&�@��L��Ͼsr�{��R��?Cu+E�����G���9|�(͊Ϣ��R�­�)�E��5.���R�N䬳Q��oϥ�m6ټ���� 好的,您得到的不是json,而是一个流 .并使用

try {
    //input is your input stream object
    File file = new File(Environment.getExternalStorageDirectory(), "filename.pdf");
    OutputStream output = new FileOutputStream(file);
    try {
        try {
            byte[] buffer = new byte[4 * 1024]; // or other buffer size
            int read;

            while ((read = input.read(buffer)) != -1) {
                output.write(buffer, 0, read);
            }
            output.flush();
        } finally {
            output.close();
        }
    } catch (Exception e) {
        e.printStackTrace(); // handle exception, define IOException and others
    }
} finally {
    input.close();
}

虽然我喜欢@insomniac的答案,但我更喜欢使用更简单的方法来保存文件流,这应该从URL读取

public void DownloadFromUrl(String url, String, dir String fileName) {
    try {
        URL url = new URL(url); //you can write here any link
        File file = new File(dir, fileName);
        URLConnection ucon = url.openConnection();
        InputStream is = ucon.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(5000);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(baf.toByteArray());
        fos.flush();
        fos.close();
    } catch (IOException e) {
    }
}
请记住添加权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

//调用下载文件(Asynctask类)。
新建DownloadFileFromURL().execute(DownloadFileUrl);
//下载url的进度对话框
受保护的对话框onCreateDialog(int id){
开关(id){
案例进度条类型://我们将其设置为0
pDialog=新建进度对话框(此对话框);
setMessage(“正在下载文件,请稍候…”);
pDialog.setUndeterminate(假);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_水平);
pDialog.setCancelable(真);
pDialog.show();
返回pDialog;
违约:
返回null;
}
}
/**
*要下载文件的后台异步任务
*/
类DownloadFileFromURL扩展异步任务{
字符串filename=“”;
/**
*在启动后台线程之前
*显示进度条对话框
*/
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
显示对话框(进度条类型);
}
/**
*在后台线程中下载文件
*/
@凌驾
受保护的字符串doInBackground(字符串…f_url){
整数计数;
试一试{
URL=新URL(f_URL[0]);
URLConnection conconnection=url.openConnection();
conconnect.connect();
//这将非常有用,以便您可以显示典型的0-100%进度条
int lenghtOfFile=conconnect.getContentLength();
字符串depo=conconnect.getHeaderField(“内容处置”);
字符串depoSplit[]=depo.split(“filename=”);
filename=depoSplit[1]。替换(“filename=”,“”)。替换(“\”,“”)。修剪();
Log.v(“,”文件名“+文件名);
//下载该文件
InputStream输入=新的BufferedInputStream(url.openStream(),8192);
//输出流
OutputStream output=新文件OutputStream(“/sdcard/”+文件名);
字节数据[]=新字节[1024];
长总计=0;
而((计数=输入。读取(数据))!=-1){
总数+=计数;
//发布进度。。。。
//在此之后,将调用onProgressUpdate
出版进度(“+(int)((总计*100)/长度文档));
//将数据写入文件
输出.写入(数据,0,计数);
}
//冲洗输出
output.flush();
//合流
output.close();
input.close();
}捕获(例外e){
Log.e(“错误:,e.getMessage());
}
返回null;
}
/**
*更新进度条
*/
受保护的void onProgressUpdate(字符串…进度){
//设置进度百分比
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
*完成后台任务后
*关闭进度对话框
**/
@凌驾
受保护的void onPostExecute(字符串文件\u url){
//下载文件后关闭对话框
解雇对话框(进度条类型);
//从SD卡读取文件路径
字符串FilePath=Environment.getExternalStorageDirectory().toString()+“/”+文件名;
Log.v(“文件路径”,“文件路径+文件路径”);
}
}

在json中,您是否获得pdf url?实际上,我无法查看所附的图像您获得的响应是什么?发布您获得的响应的示例如果您希望有人回答,请发布您的代码已发布请求和响应url。@Insmniac
//Calling the Download file (Asynctask class). 
new DownloadFileFromURL().execute(DownloadFileUrl);



//Progress dialog for download url
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case progress_bar_type: // we set this to 0
                pDialog = new ProgressDialog(this);
                pDialog.setMessage("Downloading file. Please wait...");
                pDialog.setIndeterminate(false);
                pDialog.setMax(100);
                pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                pDialog.setCancelable(true);
                pDialog.show();
                return pDialog;
            default:
                return null;
        }
    }

    /**
     * Background Async Task to download file
     */
    class DownloadFileFromURL extends AsyncTask<String, String, String> {
        String filename="";
        /**
         * Before starting background thread
         * Show Progress Bar Dialog
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(progress_bar_type);
        }

        /**
         * Downloading file in background thread
         */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection conection = url.openConnection();
                conection.connect();
                // this will be useful so that you can show a tipical 0-100% progress bar
                int lenghtOfFile = conection.getContentLength();
                String depo = conection.getHeaderField("Content-Disposition");
                String depoSplit[] = depo.split("filename=");
                filename = depoSplit[1].replace("filename=", "").replace("\"", "").trim();
                Log.v("","fileName"+filename);

                // download the file
                InputStream input = new BufferedInputStream(url.openStream(), 8192);

                // Output stream
                OutputStream output = new FileOutputStream("/sdcard/"+filename);

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                    // writing data to file
                    output.write(data, 0, count);
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();

            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

            return null;
        }

        /**
         * Updating progress bar
         */
        protected void onProgressUpdate(String... progress) {
            // setting progress percentage
            pDialog.setProgress(Integer.parseInt(progress[0]));
        }

        /**
         * After completing background task
         * Dismiss the progress dialog
         **/
        @Override
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after the file was downloaded
            dismissDialog(progress_bar_type);

            // Reading filepath from sdcard
            String FilePath = Environment.getExternalStorageDirectory().toString() + "/"+filename;

            Log.v("FilePath", "" + FilePath);
        }

    }