【发布时间】:2013-04-30 16:55:19
【问题描述】:
我正在尝试在 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();
}
}
}
}
【问题讨论】:
-
它是怎么回事我如果你做一些复杂的查询,你没有得到任何回复关闭....我在这里经历过同样的事情
-
我现在正在解决同样的问题...这是我的第一次...乍一看您的代码似乎还可以...我会尝试让它工作..如果它作品我会告诉你的