【发布时间】:2011-02-28 19:56:24
【问题描述】:
目前,我有接受 POST 数据和 FILE ($_POST / $_FILE) 的 PHP 表单。
我将如何在 Java 中使用此表单? (安卓应用)
【问题讨论】:
-
“PHP 表单”是什么意思?向 PHP 应用程序发送数据的 HTML 表单?
-
是的,我有一个 PHP 应用程序可以处理来自 HTML 表单的数据输入
目前,我有接受 POST 数据和 FILE ($_POST / $_FILE) 的 PHP 表单。
我将如何在 Java 中使用此表单? (安卓应用)
【问题讨论】:
以下是通过 Java(特别是在 Android 中)发送$_POST 的方法。转换为$_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。之后,通过 post 请求发送文件就很容易了。
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();
}
【讨论】: