我试图使用HttpUrlConnection将base64编码图像发送到服务器。我遇到的问题是大多数图像被成功发送,但有些会生成FileNotFound异常。我编码图像的代码可以在下面找到。使用HttpUrlConnection将base64编码图像发送到服务器Android
public static String encodeImage(Bitmap thumbnail) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b,Base64.URL_SAFE);
return imageEncoded;
}
当我改变行:
String imageEncoded = Base64.encodeToString(b,Base64.URL_SAFE);
到:
String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);
那么大多数图像生成FileNotFoundException异常和一些被成功发送到服务器。下面
是我HttpURLConnection类代码:
public class HttpManager {
public static String getData(RequestPackage p) {
BufferedReader reader = null;
String uri = p.getUri();
if (p.getMethod().equals("GET")) {
uri += "?" + p.getEncodedParams();
}
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod(p.getMethod());
if (p.getMethod().equals("POST")) {
con.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write(p.getEncodedParams()); //Url encoded parameters
writer.flush();
}
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
}
}
任何帮助将不胜感激。 谢谢
为什么base64在所有? – pskink
如果图像位图较大,请尝试缩小bitamp。 –
其实,问题在于服务器端... prolly,服务器块太大的请求...仍然我不明白为什么不发送纯二进制代替... – Selvin