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

Sub*_*rat 69 post android http

在android中,如何使用http将文件(数据)从移动设备发送到服务器.

Emm*_*uel 83

很简单,您可以使用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
}
Run Code Online (Sandbox Code Playgroud)

  • 能否请参考上面代码片段的ASP.NET服务器端代码? (4认同)
  • 在服务器中接收文件的参数名称是什么? (2认同)
  • 我的$ _FILES仍然是空的,我看到很多其他帖子使用MultipartEntity.我需要那个吗? (2认同)

DaG*_*RRz 16

这可以通过HTTP Post请求到服务器来完成:

HttpClient http = AndroidHttpClient.newInstance("MyApp");
HttpPost method = new HttpPost("http://url-to-server");

method.setEntity(new FileEntity(new File("path-to-file"), "application/octet-stream"));

HttpResponse response = http.execute(method);
Run Code Online (Sandbox Code Playgroud)

  • 在我的情况下,它抛出一个错误,IllegalStateException AndroidHttpClient从未关闭,我不知道如何规避它. (2认同)

小智 10

最有效的方法是使用android-async-http

您可以使用此代码上传文件:

// gather your request parameters
File myFile = new File("/path/to/file.png");
RequestParams params = new RequestParams();
try {
    params.put("profile_picture", myFile);
} catch(FileNotFoundException e) {}

// send request
AsyncHttpClient client = new AsyncHttpClient();
client.post(url, params, new AsyncHttpResponseHandler() {
    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] bytes) {
        // handle success response
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] bytes, Throwable throwable) {
        // handle failure response
    }
});
Run Code Online (Sandbox Code Playgroud)

请注意,您可以将此代码直接放入主Activity中,无需显式创建后台任务.AsyncHttp将为您解决这个问题!


slo*_*ott 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;
    }
}
Run Code Online (Sandbox Code Playgroud)