查了大量的博客,发现上传文件到httpd 可以通过命令:
curl -T testfile.txt http://localhost:8080/uploads/
但是一般android 不会用命令传文件:
上面的命令相当与用http 的put 请求方式上传文件到指定目录。
android 代码可以这样写:
/**
* @param mediaType MediaType
* @param uploadUrl put请求地址
* @param localPath 本地文件路径
* @return 响应的结果 和 HTTP status code
* @throws IOException
*/
public String put(MediaType mediaType, String uploadUrl, String localPath) throws IOException {
File file = new File(localPath);
RequestBody body = RequestBody.create(mediaType, file);
Request request = new Request.Builder()
.url(uploadUrl)
.put(body)
.build();
//修改各种 Timeout
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(600, TimeUnit.SECONDS)
.readTimeout(200, TimeUnit.SECONDS)
.writeTimeout(600, TimeUnit.SECONDS)
.build();
//如果不需要可以直接写成 OkHttpClient client = new OkHttpClient.Builder().build();
Response response = client
.newCall(request)
.execute();
return response.body().string() + ":" + response.code();
}
另外httpd 服务需要修改一些配置才支持上传文件。可以参考Apache httpd 配置可上传文件_之芫的博客-优快云博客_httpd 上传文件