从Java发送POST和FILE数据

时间:2011-02-28 19:56:24

标签: java php android

目前,我有PHP表单接受POST数据以及文件($ _POST / $ _FILE)。

我如何在Java中使用此表单? (Android应用)

3 个答案:

答案 0 :(得分:2)

以下是通过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) {
    }

}   

答案 1 :(得分:0)

因为您要将表单字段与文件字段混合,所以您需要org.apache.http.entity.mime.MultipartEntity的魔力。

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);

答案 2 :(得分:0)

下载并包含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();
        }