我試圖從Android設備上傳一個XML文件到一個將被解析的URL。作爲一個例子,我被賦予了curl命令,其工作方式:通過HTTP從Android上傳文件
curl -F [email protected] "http://the-url-to-the-server"
但是,當我嘗試從我的Android設備我不斷收到「無效的XML」作爲迴應送東西。因此,基於this answer我創建一個PHP文件爲我自己嘗試文件發送到,看看它是如何獲得派:
<?php
print_r($_FILES);
print_r($_REQUEST);
?>
我一直在嘗試各種示例代碼,但他們都非常相似,所以我認爲他們一定是正確的做法。
基本上它歸結爲:要麼我送文件時不聲明MIME類型(見FOO下文),然後得到它發送的"application/octet-stream"
,或者我加一個MIME類型"text/xml"
或"application/xml"
(見吧),然後它結束在PHP的$_REQUEST
,我假設它不是作爲一個文件發送。
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(postReceiverUrl);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("foo", new FileBody(file));
reqEntity.addPart("bar", new FileBody(file, "text/xml"));
httpPost.setEntity(reqEntity);
httpClient.execute(httpPost);
給
Array
(
[foo] => Array
(
[name] => templ2.xml
[type] => application/octet-stream
[tmp_name] => /tmp/phppWbgl8
[error] => 0
[size] => 203
)
)
Array
(
[bar] => <foo>
<bar>
</bar>
</foo>
)
一些相關的問題,這是我從試過代碼:
- Upload a file through an HTTP form, via MultipartEntityBuilder, with a progress bar
- How to upload a file using Java HttpClient library working with PHP
- http://reecon.wordpress.com/2010/04/25/uploading-files-to-http-server-using-post-android-sdk/
然後,你會改變整個請求的內容類型,我相信應該是某種形式的multipart。無論如何,我試過了,並沒有幫助。 – Niels