七、HTTP协议上传文件
- 搭建服务器,完成上传功能
- 使用浏览器上传,查看请求信息
7.1 HttpURLConnection
- 通过URL封装路径打开一个HttpURLConnection
- 设置请求方式以及头字段:Content-Type、Content-Length、Host
- 拼接数据发送
7.2 Socket
- 使用HttpURLConnection发送时内部有缓存机制,如果上传较大文件会导致内存溢出
- 我们可以使用Socket发送TCP请求,将上传数据分段发送
7.3 HttpClient
public void upload(String name, String password, String path) throws Exception {
// 创建HttpClient对象
HttpClient client = new HttpClient();
// 设置超时事件
client.getHttpConnectionManager().getParams().setConnectionTimeout(3000);
// 创建一个Post请求, 指定路径
PostMethod postMethod = new PostMethod("http://192.168.1.102:8080/14.Web/LoginServlet");
// 封装每个表单项
Part[] parts = { new StringPart("username", username), new StringPart("password", password), new FilePart("file", new File(path)) };
// 给Post请求设置实体
postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
// 执行Post请求
client.executeMethod(postMethod);
// Post请求是释放资源
postMethod.releaseConnection();
}
7.4 使用开源框架AsyncHttpClient上传
在RequestParams中添加一个File类型的字段, AsyncHttpClient就会执行上传操作
public void login(View v) throws Exception {
String username = usernameET.getText().toString().trim();
String password = passwordET.getText().toString().trim();
String path = pathET.getText().toString().trim();
RequestParams params = new RequestParams();
params.put("username", username); // URLEncoder.encode()
params.put("password", password);
params.put("upload", new File(path)); // File类型会作为上传文件字段
client.post("http://192.168.1.251:8080/WebServer/LoginServlet", params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Toast.makeText(getApplicationContext(), "登录失败 " + statusCode, Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
}
示例源码->百度网盘