2011-02-28 38 views
0

目前,我有接受POST数据以及FILE($ _POST/$ _FILE)的PHP表单。从Java发送POST和FILE数据

我该如何在Java中使用这种形式? (Android应用程序)

+0

你是什么意思的“PHP表单”?将数据发送到PHP应用程序的HTML表单? – 2011-02-28 20:00:51

+0

是的我有一个PHP应用程序,处理来自HTML表格的数据输入 – nmock 2011-02-28 20:10:19

回答

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) { 
    } 

} 
+0

您可以详细说明转换为$ _FILE吗?这是我特别困惑的部分,将它们都发送到php应用程序 – nmock 2011-02-28 21:18:36

+0

@nmock:对afk抱歉,但@fd已在此线程的另一个答案中很好地回答了此问题。 – Wroclai 2011-02-28 21:48:59

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