我正在开发一个需要打印到打印机的android应用程序。我决定使用Google Cloud Print,因为它似乎很容易设置。最初,我按照找到here的步骤集成到安卓中。这是有效的,因为它将打印到我想要的打印机。但是,对于用户来说,这个过程有点复杂。在我的例子中,过程如下:
不幸的是,我的客户不想要这个过程。他们希望用户在步骤2中单击“打印”,然后打印图片(步骤1、2和6)。因此,我不能使用Google提供的Intent,我必须使用实际的API。这需要我获得一个Google Auth令牌,获得所需的打印机,然后以这种方式提交打印作业。我执行以下操作:
我已经完成了前两个。我只是在实际打印这张照片时遇到了问题。打印图片的字节数据(Base64编码),而不是打印图片。下面是关于我如何发送请求的一些代码:
ContentResolver contentResolver = context.getContentResolver();
try {
InputStream is = contentResolver.openInputStream(uri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int n = is.read(buffer);
while (n >= 0) {
baos.write(buffer, 0, n);
n = is.read(buffer);
}
is.close();
baos.flush();
content = Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + uri.toString(), e);
} catch (IOException e) {
e.printStackTrace();
}
此代码检索图片(变量" URI“是该文件的URI),并将其转换为Base64编码的字符串。这与Google Cloud Print页面(链接到上面)上提供的PrintDialogActivity中使用的方法相同。下面是我是如何上传的:
图像
据我所知,这就是它应该是的样子。打印时收到{"success":true}的响应。但是,正如我上面所说的,它会打印出实际的Base64数据字符串。任何帮助都将不胜感激。
编辑:使用powerje下面所说的,我设法解决了这个问题。我没有使用上面的代码,而是使用了以下代码:
public void submitPrintJobWithFile(String printerId, String title, String token, String filePath, String contentType){
File file = new File(filePath);
// Method that gets the correct headers
List<Header> headers = getHeaders(contentType, token);
// Method that gets the correct post parameters
String url = CLOUDPRINT_URL + PATH_SUBMIT;
List<NameValuePair> postParams = getParams(title, contentType);
String params = "access_token=" + token + "&cookies=false" + "&printerid=" + printerId;
url += params;
response = sendMultipartData(url, file, postParams, headers);
}
private String sendMultipartData(String url, File file, List<NameValuePair> fields, List<Header> headers){
HttpPost post = new HttpPost(url);
MultipartEntity entity = new MultipartEntity();
for(NameValuePair pair : fields){
String name = pair.getName();
String value = pair.getValue();
try{
entity.addPart(name, new StringBody(value));
}catch (UnsupportedEncodingException e){
Log.d(TAG, "Error turning pair (name=" + name + ", value=" + value + ") into StringBody.");
}
entity.addPart("content", new FileBody(file));
post.setEntity(entity);
// Finish HttpClient request here...
}
https://stackoverflow.com/questions/14468266
复制相似问题