此示例适用于其中一个,但不适用于两者:
public void postData() {
//http://www.softwarepassion.com/android-series-get-post-and-multipart-post-requests/
File f = new File(filename);
try {
HttpClient client = new DefaultHttpClient();
String postURL = "http://url.com/script.php";
HttpPost post = new HttpPost(postURL);
// List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
// nameValuePairs.add(new BasicNameValuePair("project", projectName));
// nameValuePairs.add(new BasicNameValuePair("name", imageName));
// post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
FileBody bin = new FileBody(f);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("file", bin);
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
Log.i("RESPONSE",EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
}
似乎当我调用setEntity()
时,前一个实体被覆盖 - 所以我可以拥有名称值对或文件数据,但不能同时使用两者。你知道如何整合它们,所以我可以在上传中使用URL参数吗?只需将它们附加到POST URL就不起作用了。
我也试过
post.addHeader("project", projectName);
post.addHeader("name", imageName);
但这似乎也没有用。
感谢。
答案 0 :(得分:4)
这似乎可以解决问题:
reqEntity.addPart("project", new StringBody(projectName));
reqEntity.addPart("name", new StringBody(imageName));