我正在尝试在 android 中上传多部分数据,但我的代码不起作用。我的代码如下。我的上传信息主要是文本字段。所以我保留了一个 HashMap,这样键将包含字段名称,值将包含字段值。但我的解决方案不起作用。请有人让我关注我在这里做错了什么。
public static boolean uploadMultipartData(String urlString, HashMap<String, Object> dataMap){
HttpURLConnection urlConnection = null;
DataOutputStream outStream = null;
DataInputStream inStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "---------------------------265001916915724";
if (dataMap != null){
try {
StringBuffer data = new StringBuffer();
URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Connection", "Keep-Alive");
urlConnection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
outStream = new DataOutputStream(urlConnection.getOutputStream());
for (Entry<String, Object> entry : dataMap.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
outStream.writeBytes(twoHyphens + boundary + lineEnd);
outStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\""
+ lineEnd);
outStream.writeBytes(value.toString());
outStream.writeBytes(lineEnd);
}
outStream.writeBytes(twoHyphens + boundary + twoHyphens);
outStream.flush();
}
catch (MalformedURLException e) {
Log.e("DEBUG", "[MalformedURLException while sending data]");
}
catch (IOException e) {
Log.e("DEBUG", "[IOException while sending data]");
}
finally{
try {
outStream.close();
urlConnection.disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}