Sending POST and FILE data from Java
Currently, I开发者_Go百科 have PHP form that accepts POST data as well as a FILE ($_POST / $_FILE).
How would I use this form within Java? (Android app)
Here's how you can send $_POST
through Java (specifically in Android). It shouldn't be too hard convert to $_FILE
. Everything from here is a bonus.
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) {
}
}
Sounds like you need the magic of a org.apache.http.entity.mime.MultipartEntity
since you are mixing form fields with file fields.
http://hc.apache.org/httpcomponents-client-ga/apidocs/org/apache/http/entity/mime/MultipartEntity.html
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);
Download and include the Apache httpmime-4.0.1.jar and apache-mime4j-0.6.jar. After that, sending files via post request is pretty easy.
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();
}
精彩评论