之前已寫過一篇 Android 開發筆記 - HTTP、HTTPS、GET、POST、Cookie 筆記,最近則需要用 POST 上傳檔案,就順手在記一下。首先需從 http://hc.apache.org/downloads.cgi 下載 HttpClient (4.2.1) 後,從裡頭取出 httpmime-4.2.1.jar 檔拖到 Package Explorer > Your Project > libs 後,在按右鍵 Build Path > Add to Build Path...,如此一來在 Android 裡就能使用 MultipartEntity 進行上傳檔案的行為。若不使用的話,大概就自行實作鄉對應的格式也行。
PHP CGI:
<?php
echo "\nCOOKIE:<br/>\n";
print_r( $_COOKIE );
echo "\n<br/>FILES:<br/>\n";
print_r( $_FILES );
echo "\n<br/>REQUEST:<br/>\n";
print_r( $_REQUEST );
Android/Java:
public static void upload_testing() {
// config
String server = "127.0.0.1";
String cgi = "http://"+server+"/upload.php";
String file_path = "/mnt/sdcard/test.png";
// http request parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add( new BasicNameValuePair("hello", "world") ); // $_REQUEST['hello'] = 'world'
MultipartEntity entity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
// build post parameters
for( NameValuePair item : params )
try {
entity.addPart(item.getName(),new StringBody(item.getValue(), Charset.forName("UTF-8")));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// add file data
File src = new File(file_path);
if( src.exists() )
entity.addPart( "file", new FileBody( src ) ); // $_FILES['file']['name'] = 'test.png'
// use cookie
CookieStore cookies = new BasicCookieStore();
Cookie mCookie = new BasicClientCookie("CookieName", "CookieValue"); // $_COOKIE['CookieName']
((BasicClientCookie)mCookie).setPath("/");
((BasicClientCookie)mCookie).setDomain(server);
cookies.addCookie(mCookie);
// build post query
HttpPost post = new HttpPost(cgi);
post.setEntity(entity);
// do query with cookie
HttpClient client = new DefaultHttpClient();
HttpContext mHttpContext = new BasicHttpContext();
mHttpContext.setAttribute(ClientContext.COOKIE_STORE, cookies);
try {
HttpResponse response = client.execute( post, mHttpContext );
HttpEntity result = response.getEntity();
System.out.println( EntityUtils.toString(result) );
} catch (Exception e) {
e.printStackTrace();
}
}
成果:
沒有留言:
張貼留言