簡體   English   中英

從Java發送POST和FILE數據

[英]Sending POST and FILE data from Java

目前,我有PHP表單接受POST數據以及FILE($ _POST / $ _FILE)。

我如何在Java中使用此表單? (Android應用)

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

}   

聽起來你需要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);

下載並包含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();
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM