Android实现表单提交,webapi接收
1.服务端采用的是.net的WEBAPI接口。
2.android多文件上传。
以下为核心代码:
package com.example.my.androidupload; import android.util.Log; import java.io.File;
import java.io.Serializable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry; import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils; /**
* Created by wz on 2016/04/19.
*/
public class HttpClientUtil {
public final static String Method_POST = "POST";
public final static String Method_GET = "GET"; /**
* multipart/form-data类型的表单提交
*
* @param form 表单数据
*/
public static String submitForm(MultipartForm form) {
// 返回字符串
String responseStr = ""; // 创建HttpClient实例
/* HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
CloseableHttpClient httpClient = httpClientBuilder.build();*/
// CloseableHttpClient httpClient= HttpClients.createDefault(); HttpClient httpClient = new DefaultHttpClient();
try {
// 实例化提交请求
HttpPost httpPost = new HttpPost(form.getAction()); // 创建MultipartEntityBuilder
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); Log.e("HttpClientUtil", "111");
// 追加普通表单字段
Map<String, String> normalFieldMap = form.getNormalField();
for (Iterator<Entry<String, String>> iterator = normalFieldMap.entrySet().iterator(); iterator.hasNext(); ) {
Entry<String, String> entity = iterator.next();
entityBuilder.addPart(entity.getKey(), new StringBody(entity.getValue(), ContentType.create("text/plain", Consts.UTF_8)));
}
Log.e("HttpClientUtil", "222");
// 追加文件字段
Map<String, File> fileFieldMap = form.getFileField();
for (Iterator<Entry<String, File>> iterator = fileFieldMap.entrySet().iterator(); iterator.hasNext(); ) {
Entry<String, File> entity = iterator.next();
entityBuilder.addPart(entity.getKey(), new FileBody(entity.getValue()));
}
Log.e("HttpClientUtil", "333");
// 设置请求实体
httpPost.setEntity(entityBuilder.build());
Log.e("HttpClientUtil", "444");
// 发送请求
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
// 取得响应数据
HttpEntity resEntity = response.getEntity();
Log.e("HttpClientUtil", "结果:" + Integer.toString(statusCode));
if (200 == statusCode) {
if (resEntity != null) {
responseStr = EntityUtils.toString(resEntity);
}
}
} catch (Exception e) {
System.out.println("提交表单失败,原因:" + e.getMessage());
} finally {
try {
httpClient.getConnectionManager().shutdown();
} catch (Exception ex) {
}
}
return responseStr;
} /**
* 表单字段Bean
*/
public class MultipartForm implements Serializable {
/**
* 序列号
*/
private static final long serialVersionUID = -2138044819190537198L; /**
* 提交URL
**/
private String action = ""; /**
* 提交方式:POST/GET
**/
private String method = "POST"; /**
* 普通表单字段
**/
private Map<String, String> normalField = new LinkedHashMap<String, String>(); /**
* 文件字段
**/
private Map<String, File> fileField = new LinkedHashMap<String, File>(); public String getAction() {
return action;
} public void setAction(String action) {
this.action = action;
} public String getMethod() {
return method;
} public void setMethod(String method) {
this.method = method;
} public Map<String, String> getNormalField() {
return normalField;
} public void setNormalField(Map<String, String> normalField) {
this.normalField = normalField;
} public Map<String, File> getFileField() {
return fileField;
} public void setFileField(Map<String, File> fileField) {
this.fileField = fileField;
} public void addFileField(String key, File value) {
fileField.put(key, value);
} public void addNormalField(String key, String value) {
normalField.put(key, value);
}
} }
调用:
public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button mBtnUpload; @Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_upload: {
new Thread(new Runnable() {
@Override
public void run() {
HttpClientUtil httpClient = new HttpClientUtil();
HttpClientUtil.MultipartForm form = httpClient.new MultipartForm();
//设置form属性、参数
form.setAction("http://192.168.1.5:9001/api/Mobile/FileUpload/UploadFile");
String path= Environment.getExternalStorageDirectory().getPath()+"/DCIM" + "/20151120_051052.jpg";
Log.e("11", path);
File file = new File(path);
form.addFileField("file", file);
form.addNormalField("ID", "301201604");
String resultcode = httpClient.submitForm(form); Log.e("上传结果:",resultcode);
}
}).start(); break;
}
}
} @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBtnUpload = (Button) findViewById(R.id.btn_upload);
mBtnUpload.setOnClickListener(this);
}
}
服务端代码(由.net WEBAPI开发):
/// <summary>
/// 附件上传
/// </summary>
[RoutePrefix("api/Mobile/FileUpload")]
public class FileUploadController : ApiController
{
static readonly string UploadFolder = "/UpLoad/ApiUpload";
static readonly string ServerUploadFolder = HttpContext.Current.Server.MapPath(UploadFolder); #region 上传文件-文件信息不保存到数据库
/// <summary>
/// 上传文件-文件信息不保存到数据库
/// </summary>
/// <returns>返回文件信息</returns>
[HttpPost]
[Route("UploadFile")]
public async Task<List<FileResultDTO>> UploadFile()
{
Log.Info("UploadFile", "进入"); // 验证这是一个HTML表单文件上传请求
if (!Request.Content.IsMimeMultipartContent("form-data"))
{
Log.Info("UploadFile", "error01");
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
} // Create a stream provider for setting up output streams
MultipartFormDataStreamProvider streamProvider = new RenamingMultipartFormDataStreamProvider(ServerUploadFolder);
// Read the MIME multipart asynchronously content using the stream provider we just created.
await Request.Content.ReadAsMultipartAsync(streamProvider);
Log.Info("UploadFile", "进入01");
List<FileResultDTO> itemList = new List<FileResultDTO>();
foreach (MultipartFileData file in streamProvider.FileData)
{
Log.Info("UploadFile", "进入02"); FileInfo fileInfo = new FileInfo(file.LocalFileName); FileResultDTO item = new FileResultDTO();
var sLocalFileName = file.LocalFileName;
string fileName = sLocalFileName.Substring(sLocalFileName.LastIndexOf("\\") + , sLocalFileName.Length - sLocalFileName.LastIndexOf("\\") - ); item.ID = Guid.NewGuid();
item.FileName = file.Headers.ContentDisposition.FileName;
item.ServerFileName = fileInfo.Name;
item.FileSize = fileInfo.Length;
item.FilePath = UploadFolder;
item.FullFilePath = ServerUploadFolder;
item.ContentType = file.Headers.ContentType.MediaType.ToString();
item.UploadTime = DateTime.Now; itemList.Add(item);
}
Log.Info("UploadFile", "进入03");
return itemList;
}
#endregion #region 上传文件-文件信息会保存到数据库 /// <summary>
/// 上传文件-文件信息会保存到数据库
/// </summary>
/// <returns></returns>
[HttpPost]
[Route("UploadFileToServer")]
public IHttpActionResult UploadFileToServer()
{
//验证是否是 multipart/form-data
if (!Request.Content.IsMimeMultipartContent("form-data"))
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
} List<AttachmentDTO> list = new List<AttachmentDTO>();
string devId = "";
for (int i = ; i < HttpContext.Current.Request.Files.Count; i++)
{
HttpPostedFile file = HttpContext.Current.Request.Files[i]; string sFileName = "ST_M_" + Guid.NewGuid() + System.IO.Path.GetExtension(file.FileName);
string path = AppDomain.CurrentDomain.BaseDirectory + ServerUploadFolder + "/"; file.SaveAs(Path.Combine(path, sFileName)); AttachmentDTO entity = new AttachmentDTO();
devId = HttpContext.Current.Request["DevId"].ToString();
string ForeignID = HttpContext.Current.Request["ForeignID"].ToString(); entity.ForeignID = ForeignID;
entity.FileName = sFileName;
entity.FilePath = ServerUploadFolder;
entity.UploadTime = DateTime.Now;
entity.ContentType = file.ContentType;
entity.FileSize = file.ContentLength;
entity.CreatedTime = DateTime.Now; list.Add(entity);
} MobileBL.GetInstance().InsertAttachment(devId, list);
return Ok(true);
}
#endregion
}
public class RenamingMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public string Root { get; set; }
//public Func<FileUpload.PostedFile, string> OnGetLocalFileName { get; set; } public RenamingMultipartFormDataStreamProvider(string root)
: base(root)
{
Root = root;
} public override string GetLocalFileName(HttpContentHeaders headers)
{
string filePath = headers.ContentDisposition.FileName; // Multipart requests with the file name seem to always include quotes.
if (filePath.StartsWith(@"""") && filePath.EndsWith(@""""))
filePath = filePath.Substring(, filePath.Length - ); var filename = Path.GetFileName(filePath);
var extension = Path.GetExtension(filePath);
var contentType = headers.ContentType.MediaType; return "ST_M_" + Guid.NewGuid() + extension;
} }
Android Studiod代码下载:点击下载
参考:http://www.cnblogs.com/fly100/articles/3492525.html
Android实现表单提交,webapi接收的更多相关文章
- JSP表单提交与接收
JSP表单提交与接收 在Myeclipse中新建web project,在webroot中新建userRegist1.jsp,代码如下 <%@ page contentType="te ...
- 基于Http原理实现Android的图片上传和表单提交
版权声明:本文由张坤 原创文章,转载请注明出处: 文章原文链接:https://www.qcloud.com/community/article/794875001483009140 来源:腾云阁 ...
- 在IOS设备上POST提交form表单,后台接收不到值怎么办?
原文:https://blog.csdn.net/xhaimail/article/details/90440029 最近在工作上遇到一个奇葩问题,在Android和Windows平台上做请求时参数都 ...
- asp.net.mvc 中form表单提交控制器的2种方法和控制器接收页面提交数据的4种方法
MVC中表单form是怎样提交? 控制器Controller是怎样接收的? 1..cshtml 页面form提交 (1)普通方式的的提交
- SpringMVC中使用bean来接收form表单提交的参数时的注意点
这是前辈们对于SpringMVC接收表单数据记录下来的总结经验: SpringMVC接收页面表单参数 springmvc请求参数获取的几种方法 下面是我自己在使用时发现的,前辈们没有记录的细节和注意点 ...
- Java Web开发总结(三) —— request接收表单提交中文参数乱码问题
1.以POST方式提交表单中文参数的乱码问题 <%@ page language="java" import="java.util.*" pageEnco ...
- request接收表单提交数据及其中文参数乱码问题
一.request接收表单提交数据: getParameter(String)方法(常用) getParameterValues(String name)方法(常用) getParameterMap( ...
- input from 表单提交 使用 属性 disabled="disabled" 后台接收不到name="username"的值
input from 表单提交 使用 属性 disabled="disabled" 后台接收不到name="username"的值
- c#WebApi使用form表单提交excel,实现批量写入数据库
思路:用户点击下载模板按钮,获取到excel模板,然后向里面填写数据保存.from表单提交的时候选择保存好的excel,实现数据的批量导入过程 先把模板放在服务器的项目目录下面:如 模板我一般放在:F ...
随机推荐
- 读java并发编程笔记
同步策略:在共享资源上面加锁 java监视器模式:class对象-与之对应的锁(内置锁)[对象锁与class锁] 执行策略: 取消策略: =============================== ...
- CentOS6系统优化
[root@xuliangwei ~]# cat /etc/redhat-release //系统环境CentOS6.6 CentOS release 6.6 (Final) [root@xulian ...
- ES6系列_11之Set和WeakSet数据结构
一.Set 1.Set是什么? Set是ES6 提供的一种新的数据结构.类似于数组. 2.Set能解决什么问题 Set和Array 的区别是Set不允许内部有重复的值,如果有只显示一个,相当于去重. ...
- jeesite快速开发平台(一)----简介
转自:https://blog.csdn.net/u011781521/article/details/54880170
- 30.概述strust2中的拦截器
转自:https://wenku.baidu.com/view/84fa86ae360cba1aa911da02.html 拦截器是Struts2框架的核心,它主要完成解析请求参数.将请求参数赋值给A ...
- 搭建 redis 集群 (redis-cluster)
一 所需软件:Redis.Ruby语言运行环境.Redis的Ruby驱动redis-xxxx.gem.创建Redis集群的工具redis-trib.rb 二 安装配置redis redis下载地址 ...
- IT项目经理岗位职责(转)
一. 项目经理岗位职责 1. 项目经理为整个项目的第一责任人. 2. 项目经理对<质量检查报告>中的所有细则负首要责任. 3. 项目经理必须有效掌控项目开发的各个环节,协助.指导项 ...
- flume 配置说明
Flume中的HDFS Sink应该是非常常用的,其中的配置参数也比较多,在这里记录备忘一下. channel type hdfs path 写入hdfs的路径,需要包含文件系统标识,比如:hdfs: ...
- Linux基石【第二篇】虚拟网络三种连接方式(转载)
在虚拟机上安装完Centos系统后,开始配置静态IP,以方便在本宿主机上可以访问虚拟机,在曲折的配置中,了解到虚拟机还有三种连接方式:Bridged,NAT和Host-only,于是,我又一轮新的各种 ...
- Going Home(最小费用最大流)
Going Home http://poj.org/problem?id=2195 Time Limit: 1000MS Memory Limit: 65536K Total Submission ...