我怎么能写使用POST方法到PHP服务器上载了一个简单的Android文件
How can i write a simple Android file uploaded using a POST method to a PHP server
推荐答案请下载 HttpComponents 并把它添加到你的Android项目。如果要上传的文件用POST方法,你必须使用多部分。
Please download HttpComponents and add it to your Android Project. If you want to upload a file with a POST method you have to use Multipart.
private DefaultHttpClient mHttpClient; public ServerCommunication() { HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); mHttpClient = new DefaultHttpClient(params); } public void uploadUserPhoto(File image) { try { HttpPost httppost = new HttpPost("some url"); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); multipartEntity.addPart("Title", new StringBody("Title")); multipartEntity.addPart("Nick", new StringBody("Nick")); multipartEntity.addPart("Email", new StringBody("Email")); multipartEntity.addPart("Description", new StringBody(Settings.SHARE.TEXT)); multipartEntity.addPart("Image", new FileBody(image)); httppost.setEntity(multipartEntity); mHttpClient.execute(httppost, new PhotoUploadResponseHandler()); } catch (Exception e) { Log.e(ServerCommunication.class.getName(), e.getLocalizedMessage(), e); } } private class PhotoUploadResponseHandler implements ResponseHandler { @Override public Object handleResponse(HttpResponse response) throws ClientProtocolException, IOException { HttpEntity r_entity = response.getEntity(); String responseString = EntityUtils.toString(r_entity); Log.d("UPLOAD", responseString); return null; } }
来源:了Android SDK 的帖子多部分请求
另请阅读本教程的AsyncTask的例。一个AsyncTask的是有点难以code,但是如果你不使用它,你的应用程序将要上传的文件在主线程。您的应用程序将冻结在上传文件时,如果5秒钟的Android会说,你的应用程序没有响应,需要更长的时间。如果您使用的AsyncTask下载/上传文件的Android创建一个新的主题,你的应用程序也不会结冰。
Also read this tutorial for an AsyncTask example. An AsyncTask is a little bit harder to code, but if you don't use it your app is going to upload files in the main thread. Your application will freeze while uploading a file, if it takes longer then 5 seconds Android will say that your Application is not responding. If you use an AsyncTask for downloading/uploading a file Android creates a new Thread and your application won't freeze.
请注意,如果您使用多个AsyncTasks Android将当时执行AsyncTasks之一,你不能在同一时间运行多个AsyncTasks但在大多数情况下,你不就得了。
Please note that if you use multiple AsyncTasks Android will execute the AsyncTasks one at the time, you cannot run multiple AsyncTasks at the same time but in the most cases you don't have to.
更多推荐
Android的文件上传使用POST方法
发布评论