我想使用HttpClient来调用服务(localhost / png /'imageWithBase64') 这将从变量'result'返回我的回答。 Ocrad.js用图像读取基本的简单文本。
我有3个问题: - 如何将Java发送到服务的base64编码? - 是否将此id粘贴到img.src将正常工作? - 结果以JSON或HTML格式返回?
目前,我在Java中遇到了一个错误(我无法将整个String作为参数id发送到服务中)
java.lang.IllegalArgumentException: Illegal character in path
Code Java:
File file = new File(getClass().getClassLoader().getResource("test.png").getFile());
String encodedFile = Base64.encode(FileUtils.readFileToByteArray(file));
String url = "http://127.0.0.1:3000/png/"+encodedFile;
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
我的Java依赖关系:
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
带有nodeJS的服务器:
var express = require('express');
var OCRAD = require('ocrad.js');
var Canvas = require('canvas');
var Image = Canvas.Image;
var app = express();
app.get('/png/:id', function(req, res) {
var img = new Image();
img.src = 'data:image/png;base64,'+req.params.id;
var canvas = new Canvas(img.width, img.height);
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, img.width, img.height);
var result = OCRAD(canvas);
res.send({result:result});
});
app.listen(3000);
console.log('Listening on port 3000...');