有时候需要通过Android客户端向服务器提交数据,带一些参数、图片或其他文件,那么可以用如下方法,模拟post提交
例如网页中有个表单,如下
<form action="xxx.action" method="post" enctype="multipart/form-data">
<input type="text" name="name" /><br />
<input type="file" name="file" /><br />
<input type="submit" />
</form>
我们可以在Android客户端模拟post方式提交,以达到上面的效果
/**
* 提交数据
* @param url 服务端地址
* @param param 参数集合
* @param file 图片文件
* @param cookie 登录后返回的cookie,无登录验证可为null
* @return 服务器返回结果
* @throws Exception
*/
public static String uploadSubmit(String url, Map<String, String> param,
File file, String cookie) throws Exception {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
if(cookie != null && cookie.length()>0){
//向头信息添加cookie
post.addHeader("cookie", cookie);
}
MultipartEntity entity = new MultipartEntity();
if (param != null && !param.isEmpty()) {
for (Map.Entry<String, String> entry : param.entrySet()) {
if (entry.getValue() != null
&& entry.getValue().trim().length() > 0) {
entity.addPart(entry.getKey(),
new StringBody(entry.getValue()));
}
}
}
if (file != null && file.exists()) {
entity.addPart("file", new FileBody(file));
}
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
int stateCode = response.getStatusLine().getStatusCode();
StringBuffer sb = new StringBuffer();
if (stateCode == HttpStatus.SC_OK) {
HttpEntity result = response.getEntity();
if (result != null) {
InputStream is = result.getContent();
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
String tempLine;
while ((tempLine = br.readLine()) != null) {
sb.append(tempLine);
}
}
}
post.abort();
return sb.toString();
}