为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用http将Android中的文件从移动设备发送到服务器?

如何使用http将Android中的文件从移动设备发送到服务器?

aluckdog 2019-07-09 10:26:29
如何使用http将Android中的文件从移动设备发送到服务器?在Android中,如何使用http将文件(数据)从移动设备发送到服务器。
查看完整描述

3 回答

?
GCT1015

TA贡献1827条经验 获得超4个赞

简单来说,您可以使用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}


查看完整回答
反对 回复 2019-07-09
?
富国沪深

TA贡献1790条经验 获得超9个赞

这可以通过向服务器发出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);


查看完整回答
反对 回复 2019-07-09
?
眼眸繁星

TA贡献1873条经验 获得超9个赞

将其全部封装在异步任务中,以避免线程错误。

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;
    }}


查看完整回答
反对 回复 2019-07-09
  • 3 回答
  • 0 关注
  • 575 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信