Android的文件上传使用POST方法

编程入门 行业动态 更新时间:2024-10-23 07:35:49
本文介绍了Android的文件上传使用POST方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我怎么能写使用POST方法到PHP服务器上载了一个简单的Andr​​oid文件

How can i write a simple Android file uploaded using a POST method to a PHP server

推荐答案

请下载 HttpComponents 并把它添加到你的Andr​​oid项目。如果要上传的文件用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秒钟的Andr​​oid会说,你的应用程序没有响应,需要更长的时间。如果您使用的AsyncTask下载/上传文件的Andr​​oid创建一个新的主题,你的应用程序也不会结冰。

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方法

本文发布于:2023-10-11 22:43:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1483047.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件上传   方法   Android   POST

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!