我正在尝试将手机/模拟器相机拍摄的照片发送到 Node.js 服务器,因此我对其进行编码以发出字符串 POST 请求。
我尝试使用互联网上的其他答案(使用字节数组流和位图的压缩版本)对其进行编码。在 Node.js 上,我尝试使用肯定有效的函数对其进行解码;问题是从 Java 发送到 Node.js 的编码是错误的。
这是位图的编码:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
final String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
我对字符串的 POST 请求如下所示(我使用 Volley 进行服务器交互):
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
@Override
public void onResponse(String response) {
// response
Log.d("RESPONSE", response);
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", "ERROR" + error);
}
}
) {
@Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("image", imageEncoded);
return params;
}
};
VolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(postRequest);
我很确定问题是我的编码在发送到服务器时会收到一些额外的 % 字符,因此无法很好地解码。我认为在我的 Node.js 代码中我必须使用 block 来生成完整的字符串,如下所示:
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
let body = [];
req.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
body = Buffer.concat(body).toString();
body = body.split('=');
// More code here
}
我的 body 看起来像
"image=iVBORw0KGgoAAAANSUhEUgAAAHgAAACgCAIAAABIaz%2FH..."
所以我不得不使用 split 来仅获取编码,但仍然不起作用。有没有办法将此字符串转换为另一个不是像这样进行 URL 编码的字符串?或者不做这样的修改就可以通过POST请求?
最佳答案
看来您正在使用 Volley 库。如果是这样,您应该考虑使用 JSONObjectRequest 而不是 StringRequest。将图像转换为 JSON 字符串格式后,它看起来像这样:
String myImage = "{image:" + imageEncoded + "}"
JSONObject obj = null;
try {
obj = new JSONObject(myImage);
} catch (JSONException e1) {
e1.printStackTrace();
}
JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.POST,url,obj,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
)} {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json; charset=utf-8");
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
关于java - 从 Android 向 Node.js 服务器发送图像会以 URL 样式进行编码,无法很好地解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56997771/