猿问
回到首页
个人中心
反馈问题
注册登录
下载APP
首页
课程
实战
体系课
手记
专栏
慕课教程
如何使用http将Android中的文件从移动设备发送到服务器?
如何使用http将Android中的文件从移动设备发送到服务器?
在Android中,如何使用http将文件(数据)从移动设备发送到服务器。
aluckdog
浏览 576
回答 3
3回答
GCT1015
简单来说,您可以使用POST请求并以二进制(字节数组)的形式提交文件。String url = "http://yourserver";File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "yourfile");try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); InputStreamEntity reqEntity = new InputStreamEntity( new FileInputStream(file), -1); reqEntity.setContentType("binary/octet-stream"); reqEntity.setChunked(true); // Send in multiple parts if needed httppost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httppost); //Do something with response...} catch (Exception e) { // show error}
0
0
0
富国沪深
这可以通过向服务器发出HTTP POST请求来完成:HttpClient http = AndroidHttpClient.newInstance("MyApp");HttpPost method = new HttpPost(" method.setEntity(new FileEntity(new File("path-to-file"), "application/octet-stream"));HttpResponse response = http.execute(method);
0
0
0
眼眸繁星
将其全部封装在异步任务中,以避免线程错误。public class AsyncHttpPostTask extends AsyncTask<File, Void, String> { private static final String TAG = AsyncHttpPostTask.class.getSimpleName(); private String server; public AsyncHttpPostTask(final String server) { this.server = server; } @Override protected String doInBackground(File... params) { Log.d(TAG, "doInBackground"); HttpClient http = AndroidHttpClient.newInstance("MyApp"); HttpPost method = new HttpPost(this.server); method.setEntity(new FileEntity(params[0], "text/plain")); try { HttpResponse response = http.execute(method); BufferedReader rd = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); final StringBuilder out = new StringBuilder(); String line; try { while ((line = rd.readLine()) != null) { out.append(line); } } catch (Exception e) {} // wr.close(); try { rd.close(); } catch (IOException e) { e.printStackTrace(); } // final String serverResponse = slurp(is); Log.d(TAG, "serverResponse: " + out.toString()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }}
0
0
0
打开App,查看更多内容
随时随地看视频
慕课网APP
相关分类
Android
继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续