我正在尝试使用一些相关的字符串数据发送两个图像。图像采用Base64字符串的形式。参数的总长度约为81000
这是我的代码:
HttpPost post = new HttpPost(postURL);
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entityBuilder.addPart("uname", new StringBody(GlobalUname, ContentType.TEXT_PLAIN));
entityBuilder.addPart("pwd", new StringBody(GlobalPassword, ContentType.TEXT_PLAIN));
entityBuilder.addPart("imeino", new StringBody(IMEINumber, ContentType.TEXT_PLAIN));
entityBuilder.addPart("role", new StringBody(role_code, ContentType.TEXT_PLAIN));
entityBuilder.addPart("filexml", new StringBody(Msr_encryXmlFile, ContentType.TEXT_PLAIN));
entityBuilder.addPart("img1", new StringBody(images.get(0), ContentType.TEXT_PLAIN));
entityBuilder.addPart("img2", new StringBody(images.get(1), ContentType.TEXT_PLAIN));
HttpEntity entity = entityBuilder.build();
post.setEntity(entity);
HttpResponse responsePOST = client.execute(post);
但我得到“”(空白字符串)作为回应。
我尝试将这些图像作为FileBody
发送,但我仍然得到相同的结果。
上述代码适用于单张图像。
我尝试了HttpUrlConnection
URL url = new URL(postURL);
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("POST");
http.setInstanceFollowRedirects(false);
http.setDoOutput(false);
Map<String,String> arguments = new HashMap<>();
arguments.put("uname", GlobalUname);
arguments.put("pwd", GlobalPassword);
arguments.put("imeino", IMEINumber);
arguments.put("role", role_code);
arguments.put("filexml", Msr_encryXmlFile);
arguments.put("img1", imagePath.get(0));
arguments.put("img2", imagePath.get(1));
StringBuilder strBuilder = new StringBuilder("&");
for(Map.Entry<String,String> entry : arguments.entrySet())
strBuilder.append(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + URLEncoder.encode(entry.getValue(), "UTF-8"));
byte[] out = strBuilder.toString().getBytes(Charset.forName("UTF-8"));
int length = out.length;
http.setFixedLengthStreamingMode(length);
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.connect();
/*PrintWriter printWriter = new PrintWriter(http.getOutputStream());
printWriter.print(out);
printWriter.close();*/
http.getOutputStream().write(out);
int code = http.getResponseCode();
String msg = http.getResponseMessage();
Reader in = new BufferedReader(new InputStreamReader(http.getInputStream(), "UTF-8"));
我将状态代码400
视为错误请求。
如何完成它。
这是我的服务器代码:
Public Function getMustrollNew() As System.Xml.XmlElement Implements Imustroll.getMustrollNew
Dim uname, finyear As String
check = New HandheldErrorLOg
download_id = Guid.NewGuid()
Try
Dim con1 As String
finyear = HttpContext.Current.Request.Form("finyear")
uname = HttpContext.Current.Request.Form("uname")
'pwd = mps.decrypt(Split(mps.decrypt(HttpContext.Current.Request.Form("pwd")), "||")(0))
pwd = HttpContext.Current.Request.Form("pwd")
Dim image1 as String = HttpContext.Current.Request.Form("img1")
Dim image2 as String = HttpContext.Current.Request.Form("img2")
imeino = mps.decrypt(HttpContext.Current.Request.Form("imeino"))
'Rest of code
End Function
答案 0 :(得分:0)
当我发送3张图片时,我也遇到了同样的问题。然后我现在解决了这个问题。
首先,检查数据库字段大小。如果字段的大小小于Base64字符串,则会产生问题。
在我的情况下,我用我的moto g4 plus mobile拍摄照片。当我拍摄图像时,图像的大小接近5MB。因此,Base64 String给出的字符串长度接近72,00,000。它的尺寸非常大。所以。我无法将3张图像成功发送到服务器。然后我将图像大小减小到250 kb。因此,Base64 String给出的字符串长度接近50k。这是一个非常大的差异。之后,我可以一次成功上传3张图片
请尝试以下代码,让我知道您仍然面临这个问题。
public static File file = null;
int TAKE_PICTURE = 1;
public static Uri imageUri;
private void cameraActivity(){
SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.US);
Date now = new Date();
String fileName = formatter.format(now) + ".JPEG";
Intent intentCamera = new Intent("android.media.action.IMAGE_CAPTURE");
file = new File(Environment.getExternalStorageDirectory()+"/folder/", fileName);
imageUri = Uri.fromFile(file);
intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intentCamera, TAKE_PICTURE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intentFromCamera) {
super.onActivityResult(requestCode, resultCode, intentFromCamera);
if (resultCode == RESULT_OK && requestCode == TAKE_PICTURE) {
if(file.exists()) {
ExifInterface oldExif = null;
String OldExifOrientation = null;
try {
oldExif = new ExifInterface(file.getAbsolutePath());
OldExifOrientation = oldExif.getAttribute(ExifInterface.TAG_ORIENTATION);
} catch (IOException e) {
e.printStackTrace();
}
scaleDown(BitmapFactory.decodeFile(file.getAbsolutePath()), 400, true);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
if (OldExifOrientation != null) {
try {
ExifInterface newExif = new ExifInterface(file.getAbsolutePath());
newExif.setAttribute(ExifInterface.TAG_ORIENTATION, OldExifOrientation);
newExif.saveAttributes();
} catch (IOException e) {
e.printStackTrace();
}
}
sendImageRequest();
}
}
}
private void sendImageRequest() {
String encodedImage = "";
if(file!=null) {
if(file.exists()){
Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
Log.e("path : ", "--" + file.getPath());
Log.e("name : ", "--" + file.getName());
Log.e("AbsolutePath : ", "--" + file.getAbsolutePath());
Log.e("length : ", "--" + encodedImage.length());
}
}
**//your server request code here**
}
public Bitmap scaleDown(Bitmap realImage, float maxImageSize,
boolean filter) {
float ratio = Math.min(
(float) maxImageSize / realImage.getWidth(),
(float) maxImageSize / realImage.getHeight());
int width = Math.round((float) ratio * realImage.getWidth());
int height = Math.round((float) ratio * realImage.getHeight());
Bitmap newBitmap = Bitmap.createScaledBitmap(realImage, width,
height, filter);
saveToInternalStorage(newBitmap);
return newBitmap;
}
private String saveToInternalStorage(Bitmap bitmapImage){
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return file.getAbsolutePath();
}