目前我正在做一个需要在服务器数据库上发布数据的项目。在这里,我发布了name
, id
,image
等数据。
我想将图像作为二进制数据传递。为此,我将图像转换为 base64 字符串,然后 POST 数据,但由于图像分辨率或 HTTP 连接大小较大,我收到 413 错误代码,表明 URL 太大。
请问谁能给我解决方案?在这里,我给你我已经实现的代码。
价值观
Bitmap b1 = (Bitmap) data.getExtras().get("data");
b1=Bitmap.createScaledBitmap(b1, 100,100, true);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
b1.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String base64String = Base64.encodeBytes(b);
Log.e("Base 64 conversion of image--------", base64String);
response = webService.doNetworkConnection("{\"method\":\"EventUploadPhoto\",\"data\":{\"ClientCode\":"
+ "\""
+ Util.clientCode
+ "\""
+ ",\"EventID\":"
+ "\""
+ itemId
+ "\""
+ ",\"ImageName\":"
+ "\""
+ filename
+ System.currentTimeMillis()
+ "\""
+ ",\"ImageData\":"
+ "\""
+ imgData
+ "\""
+ ",\"UserName\":"
+ "\""
+ username
+ "\""
+ ",\"TokenId\":"
+ "\""
+ tokenid
+ "\"" + "}}", "POST");
做网络连接
public String doNetworkConnection(String request, String methodType) throws IOException {
String str = java.net.URLEncoder.encode(request, "UTF-8");
String resultstring = "";
System.out.println("string request:" + request);
int response = -1;
try {
URL url = new URL((mContext.getResources()
.getString(R.string.WebServiceUrl))
+ "" + str);
System.out.println("url:" + url);
URLConnection conn = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
httpConn.connect();
response = httpConn.getResponseCode();
System.out.println("response code:" + response);
if (response == HttpURLConnection.HTTP_OK) {
InputStream is = httpConn.getInputStream();
resultstring = convertinputStreamToString(is);
} else {
resultstring = "";
}
} catch (Exception e) {
resultstring = "";
}
System.out.println("result string:" + resultstring);
return resultstring;
}
这里的 HTTP 响应代码是 413,所以它告诉 URL 太大,不能 POST 图像。