我想使用经纬度的MultipartEntity.Values发送图像和经度值,并将其存储在名为plat和plong的单独变量中。我能够将图像发送到服务器,但不能同时发送经纬度。在服务器端,只有Latitude最终插入到数据库中。 Bellow是我用来将文件和字符串发送到服务器的代码。任何人都可以建议我在哪里做错了?如何使用Android的MultipartEntity发送多个字符串变量
private class UploadTask extends AsyncTask<Bitmap, Void, Void> {
protected Void doInBackground(Bitmap... bitmaps) {
if (bitmaps[0] == null)
return null;
setProgress(0);
Bitmap bitmap = bitmaps[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); // convert
// Bitmap
// to
// ByteArrayOutputStream
InputStream in = new ByteArrayInputStream(stream.toByteArray()); // convert
// ByteArrayOutputStream
// to
// ByteArrayInputStream
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost(
"http://www.example.com/index.php"); // server
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("myFile",
System.currentTimeMillis() + ".jpg", in);
httppost.setEntity(reqEntity);
reqEntity.addPart("long",String.valueOf(plong));
reqEntity.addPart("lat",String.valueOf(plat));
Log.e(TAG, "request " + httppost.getRequestLine());
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (response != null)
Log.i(TAG, "response "
+ response.getStatusLine().toString());
} finally {
}
} finally {
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
以下是MultipartEntity类中的addPart()方法。
ByteArrayOutputStream out = new ByteArrayOutputStream();
public void addPart(final String key, final String value) {
writeFirstBoundaryIfNeeds();
try {
out.write(("Content-Disposition: form-data; name=\"" +key+"\"\r\n").getBytes());
out.write("Content-Type: text/plain; charset=UTF-8\r\n".getBytes());
out.write("Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes());
out.write(value.getBytes());
out.write(("\r\n--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
我试过,但我对StringBody收到错误要我做出StringBody类或更改为不同的字符串方法。 – user3393926 2014-11-05 06:27:38
你必须下载jar“httpmime-4.03” – 2014-11-05 07:18:44
通过这个链接下载jar: - http://www.java2s.com/Code/Jar/h/Downloadhttpmime411jar.htm – 2014-11-05 07:32:18