2011-02-28 63 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(); 
     }