从Java发送POST和FILE数据
答
下面是你可以通过Java发送$_POST
(特别是在Android设备)。它不应该太难转换为$_FILE
。这里的一切都是奖金。
public void sendPostData(String url, String text) {
// Setup a HTTP client, HttpPost (that contains data you wanna send) and
// a HttpResponse that gonna catch a response.
DefaultHttpClient postClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse response;
try {
// Make a List. Increase the size as you wish.
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
// Add your form name and a text that belongs to the actual form.
nameValuePairs.add(new BasicNameValuePair("your_form_name", text));
// Set the entity of your HttpPost.
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute your request against the given url and catch the response.
response = postClient.execute(httpPost);
// Status code 200 == successfully posted data.
if(response.getStatusLine().getStatusCode() == 200) {
// Do something. Maybe you wanna get your response
// and see what it contains, with HttpEntity class?
}
} catch (Exception e) {
}
}
答
听起来像是你需要一个org.apache.http.entity.mime.MultipartEntity
的神奇,因为你用文件中的字段混合表单域。
File fileObject = ...;
MultiPartEntity entity = new MultiPartEntity();
entity.addPart("exampleField", new StringBody("exampleValue")); // probably need to URL encode Strings
entity.addPart("exampleFile", new FileBody(fileObject));
httpPost.setEntity(entity);
答
下载,其中包括了Apache httpmime-4.0.1.jar和Apache的mime4j-0.6.jar。之后,通过发布请求发送文件非常简单。
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost("http://url.to.your/html-form.php");
try {
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("file", new FileBody(new File("/sdcard/my_file_to_upload.jpg")));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,
localContext);
Log.e(this.getClass().getSimpleName(), response.toString());
} catch (IOException e) {
e.printStackTrace();
}
你是什么意思的“PHP表单”?将数据发送到PHP应用程序的HTML表单? – 2011-02-28 20:00:51
是的我有一个PHP应用程序,处理来自HTML表格的数据输入 – nmock 2011-02-28 20:10:19