Android Google CloudPrint 通过 URL API 提交 PDF 打印作业

Android Google CloudPrint Submit a PDF print job via URL API

我无法获取正确的代码来发送包含 PDF 的多部分表单到 google 云打印(我没有使用 android 中的内置意图的原因是你无法自动 select 打印机,使用 intent 时需要手动完成)

我一直在使用 Volley 提交它,但我一直在阅读它对大文件的影响不大?

 final RequestQueue queue =       Volley1.getInstance(this).getRequestQueue();
            String url3 = "https://www.google.com/cloudprint/submit";
            final VolleyMultipartRequest multipartRequest = new       VolleyMultipartRequest(Request.Method.POST, url3 ,new             Response.Listener<NetworkResponse>() {

                    @Override
                    public void onResponse(NetworkResponse response) {
                            String resultResponse = new             String(response.data);
                            Log.d("responseis",resultResponse);
                    }
            }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                            error.printStackTrace();
                    }
            }){
                    @Override
                    protected Map<String, String> getParams() {

                            Map<String, String>  params = new HashMap<>();
                            // the POST parameters:
                            params.put("redirect_uri", "xxxxx");
                            params.put("printerid","xxxxxx");
                            params.put("title", "result1.pdf");
                            params.put("contentType", "application/pdf");
                            params.put("ticket", "{\"print\":{},\"version\":\"1.0\"}");
                            params.put("hl", "en");
                            return params;
                    }
                    @Override
                    public Map getHeaders() throws AuthFailureError {
                            Map headers = new HashMap();
                            headers.put("Authorization", "OAuth"+" "+res);
                            headers.put("Content-Type", "multipart/form-data; boundary=__1466595844361__");
                            //headers.put("Content-Type","application/x-www-form-urlencoded");
                            //Logger.debugE(Constants.accesstoken, headers.toString());
                            return headers;
                    }
                    @Override
                    protected Map<String, DataPart> getByteData() {
                            Map<String, DataPart> params = new HashMap<>();
                            //String yourFilePath =       Environment.getExternalStorageDirectory().getAbsolutePath()+ "/PDFs/result1.pdf";
                            String yourFilePath=Environment.getExternalStorageDirectory().getAbsolutePath()+ "/PDFs/result1.pdf";
                            File dir = new File(Environment.getExternalStoragePublicDirectory(
                                    Environment.DIRECTORY_DOWNLOADS), "PDF_reader");

                            File text = new File(dir + File.separator +  "test_r.pdf");
                            String input = text.getAbsolutePath();
                            byte[] data = new byte[(int) input.length()];
                            try {
                                    //convert file into array of bytes
                                     data = FileUtils.readFileToByteArray(text);

                            }catch(Exception e){
                                    e.printStackTrace();
                            }

                            params.put("content", new DataPart("result1.pdf",data , "application/pdf"));
                            return params;
                    }
            };
 queue.add(multipartrequest);

经过反复试验,我最终使用了 OKHTTP 库,并且能够使用 API 成功地将打印作业提交到 google 云打印。获取包含 pdf 文件的多部分表单有点棘手,但正确的工作请求如下。显然token和printerid是在其他请求中获取的,需要手动添加。

public void run() throws Exception {

//File directory
File dir = Environment.getExternalStorageDirectory();
File file = new File(dir, "PDFs/result1.pdf");
if(file.canRead()){
    Log.d("file", "can read");
}else {Log.d("file","cant read");};


// Final request body
RequestBody requestBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("content","result1.pdf",RequestBody.create(MediaType.parse("application/pdf"), file))
        .build();

//URL Parameters
HttpUrl url = new HttpUrl.Builder()
        .scheme("https")
        .host("www.google.com")
        .addPathSegments("cloudprint/submit")
        .addQueryParameter("printerid", "82d70sde-694b-3385-f263-164cb04320c3")
        .build();

Request request = new Request.Builder()
        .header("Authorization", "OAuth ya29.Cl0jAxDuQni_Dskz6Y2r-wRaJVMxEw8fy5hPNfAm02pDLnZc9HX-RfHpmMoS0OL-Wv_SKxBtYIwRK9jVpJDwl7Qs-RFt02Qc5Yoid4w1kV8b4vBIpcleIQ8lBEto")
        .url(url)
        .post(requestBody)
        .build();

client.newCall(request)
        .enqueue(new Callback() {
            @Override
            public void onFailure(final Call call, IOException e) {
                // Error

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // For the example, you can show an error dialog or a toast
                        // on the main UI thread
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                String res = response.body().string();

                // Do something with the response
            }
        });
}