从php发送pdf文件到android

时间:2013-12-24 13:48:30

标签: php android pdf

我从android获取数据并将它们发送到php,在那里创建pdf并发送回android。我得到的只是sd卡根目录下的空pdf文件。任何人都可以帮助我吗?

public class MainActivity extends Activity {

    Button go;
    EditText name;
    EditText pass;
    Spinner date;
    String path;
    String dat;
    String month;
    String username;
    String password;
    String url1 = "http://localhost/test.php";


    ProgressBar pb;
    Dialog dialog;
    int downloadedSize = 0;
    int totalSize = 0;
    TextView cur_val;

    HttpURLConnection connection = null;
    String pathToOurFile = "/";

     HttpClient httpclient = new DefaultHttpClient();
     HttpPost httppost = new HttpPost(url1);




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        go = (Button) findViewById(R.id.button1);
        name = (EditText) findViewById(R.id.editText1);
        pass = (EditText) findViewById(R.id.editText2);
        date = (Spinner) findViewById(R.id.spinner1);




        go.setOnClickListener(new View.OnClickListener() {

            private StringBuilder inputStreamToString(InputStream is) {
                String line = "";
                StringBuilder total = new StringBuilder();

                // Wrap a BufferedReader around the InputStream
                BufferedReader rd = new BufferedReader(new InputStreamReader(is));

                // Read response until the end
                try {
                    while ((line = rd.readLine()) != null) { 
                        total.append(line); 
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                // Return full string
                return total;
            }

            @Override
            public void onClick(View v) {
                //showProgress(url1);

                new Thread(new Runnable() {
                    public void run() {
                         downloadFile();
                    }
                  }).start();  

                  username = name.getText().toString();
                  password = pass.getText().toString();

                  TextView selection = (TextView)date.getSelectedView();
                  CharSequence dat = selection.getText();
                  month = dat.toString().toLowerCase();


                  StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                    StrictMode.setThreadPolicy(policy);

                    try {
                        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

                        nameValuePairs.add(new BasicNameValuePair("username", username));
                        nameValuePairs.add(new BasicNameValuePair("password", password));
                        nameValuePairs.add(new BasicNameValuePair("month", month));
                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                        HttpResponse response = httpclient.execute(httppost);

                        inputStreamToString(response.getEntity().getContent());


                    } catch (ClientProtocolException e) {
                        e.printStackTrace();                        
                    } catch (IOException e) {
                        e.printStackTrace();                    
                    }

            }
        });        


    }

    void downloadFile(){
        String fileName = username+"_"+month+".pdf";
        try {
            URL url = new URL(url1);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);

            //connect
            urlConnection.connect();

            //set the path where we want to save the file           
            File SDCardRoot = Environment.getExternalStorageDirectory(); 
            //create a new file, to save the downloaded file 
            File file = new File(SDCardRoot,fileName);

            FileOutputStream fileOutput = new FileOutputStream(file);

            //Stream used for reading the data from the internet
            InputStream inputStream = connection.getInputStream();

            //this is the total size of the file which we are downloading
            totalSize = connection.getContentLength();

            runOnUiThread(new Runnable() {
                public void run() {
                    pb.setMax(totalSize);
                }               
            });

            //create a buffer...
            byte[] buffer = new byte[1024];
            int bufferLength = 0;

            while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                fileOutput.write(buffer, 0, bufferLength);
                downloadedSize += bufferLength;
                // update the progressbar //
                runOnUiThread(new Runnable() {
                    public void run() {
                        pb.setProgress(downloadedSize);
                        float per = ((float)downloadedSize/totalSize) * 100;
                        cur_val.setText("Downloaded " + downloadedSize + "KB / " + totalSize + "KB (" + (int)per + "%)" );
                    }
                });
            }
            //close the output stream when complete //
            fileOutput.close();
            runOnUiThread(new Runnable() {
                public void run() {
                    // pb.dismiss(); // if you want close it..
                }
            });         

        } catch (final MalformedURLException e) {
            showError("Error : MalformedURLException " + e);        
            e.printStackTrace();
        } catch (final IOException e) {
            showError("Error : IOException " + e);          
            e.printStackTrace();
        }
        catch (final Exception e) {
            showError("Error : Please check your internet connection " + e);
        }       
    }

    void showError(final String err){
        runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(MainActivity.this, err, Toast.LENGTH_LONG).show();
            }
        });
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

日志

12-24 14:38:43.810:E / Trace(5419):错误打开跟踪文件:没有这样的文件或目录(2) 12-24 14:38:44.800:E / copybit(5419):打开帧缓冲区错误errno = 13(权限被拒绝) 12-24 14:38:54.970:E / copybit(5419):打开帧缓冲区错误errno = 13(权限被拒绝)

3 个答案:

答案 0 :(得分:0)

将网址网址 = http://localhost/test.php更改为http://10.0.2.2/test.php

答案 1 :(得分:0)

您正在尝试访问Android上的localhost,但这不起作用。您的日志未显示,但connection.getInputStream()是抛出异常的位置。这是在您打开文件后,因此您在SD卡上获得一个空文件。

您需要将http://localhost/test.php替换为您设备所在网络上可访问的有效网址。

答案 2 :(得分:0)

确保您具有启用浏览器存储的权限,检查设置,应用程序,浏览器的权限