目前,我有一个接受 POST 数据和 FILE ($_POST/$_FILE) 的 PHP 表单。
我如何在 Java 中使用这个表单? (Android 应用程序)
最佳答案
以下是如何通过 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) {
}
}
关于java - 从 Java 发送 POST 和 FILE 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5146884/