android 接口传值,Android调用WebAPI之传参、文件

最近把后台改成 WebAPI ,客户端向后台传参数、文件时碰到些问题:

一、传参数

用 JQuery ajax 调用后台方法时,后台方法一般定义成这样:

[WebMethod]

[Authorize]

public string GetCustomList(string CustomerName, string Name, string Loc_Name, string selectStorageState)

{

}

前台这样调用:

$.ajax({

type: "POST",

url: "/Home/GetCustomList",

data: "{ \"CustomerName\":\"" + $("#CustomerName").val() + "\",\"Name\": \"" + $("#Name").val() + "\",\"Loc_Name\": \"" + $("#Loc_Name").val() + "\",\"selectStorageState\": \"" + $("#selectStorageState").val() + "\" }",

contentType: "application/json; charset=utf-8",

dataType: "json",

success: function (msg) {

},

error: function (xhr, msg) { alert(msg); }

});

用这种方法传参在 WebAPI 里会报下面的错误:

Can’t bind multiple parameters (‘foo’ and ‘bar’) to the request’s content.

可以有以下方法解决这个报错

1、后台封装成类

WebAPI 后台:

public class User

{

public string user_name { get; set; }

public string user_password { get; set; }

}

[HttpPost]

public string Login([FromBody]User user)

{

}

Android 前台:

List nameValuePairs = new ArrayList();

nameValuePairs.add(new BasicNameValuePair("user_name", mUserName));

nameValuePairs.add(new BasicNameValuePair("user_password", mPassword));

String resultString="";

try {

resultString= HttpHelper.invokePost("Login", nameValuePairs);

} catch (Exception e) {

}

2、拼 json

WebAPI 后台

[HttpPost]

[Authorize]

public string GetStockList([FromBody]string jsonString)

{

JObject jObject = JObject.Parse(jsonString);

page = Convert.ToInt32(jObject["page"].ToString());

pageSize = Convert.ToInt32(jObject["pageSize"].ToString());

}

Android 前台

String jsonString = "{\"page\":\""+sPage+"\",\"pageSize\":\""+sPageSize+"\"}";

List nameValuePairs = new ArrayList();

nameValuePairs.add(new BasicNameValuePair("", jsonString));

String resultString= HttpHelper.invokePost("GetStockList", nameValuePairs);

二、传文件

WebAPI 后台

[Authorize]

public Task Add_Img()

{

string root = HttpContext.Current.Server.MapPath("~");

string tmpRoot = root + "/App_Data";

var provider = new MultipartFormDataStreamProvider(tmpRoot);

//Read the form data and return an async task.//读取表单数据,并返回一个async任务

string sName = "88";

string nName = "";

string FilePath = "Uploads/";

Request.Content.Headers.ContentType.CharSet = "UTF-8";

var task = Request.Content.ReadAsMultipartAsync(provider).

ContinueWith(t =>

{

sName = provider.FileData[0].LocalFileName;

string GpsImgJson = provider.FormData["GpsImgJson"];

GpsImgJson = HttpUtility.UrlDecode(GpsImgJson, Encoding.GetEncoding("UTF-8"));

GpsImg gpsImg = JsonHelper.JsonDeserialize(GpsImgJson);

nName = gpsImg.FileName;

FilePath += nName;

if (!File.Exists(root + "/" + FilePath))

{

File.Move(sName, root + "/" + FilePath);

}

//保存

if (true)

{

return Request.CreateResponse(HttpStatusCode.OK, "上传成功");

}

else

{

return Request.CreateResponse(HttpStatusCode.InternalServerError, "保存出错!");

}

});

return task;

}

Android 前台

String jsonString = "{\"Title\":\""+myTitleText.getText().toString()+

"\",\"Content\":\""+myContentText.getText().toString()+

"\",\"FileName\":\""+filename+

"\",\"Longitude\":\""+lonString+"\",\"Latitude\":\""+latString+"\"}";

Map params0 = new HashMap();

params0.put("GpsImgJson", jsonString);

String st= HttpHelper.invokePost("AddImg", mImageUri.getPath(), params0);

public static String invokePost(String action, String filePath, Map params) {

try {

String url = API_URL + action + "/";

Log.d(TAG, "url is" + url);

HttpPost httpPost = new HttpPost(url);

File file = new File(filePath);

MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,null,Charset.forName("UTF-8"));

FileBody fb = new FileBody(file);

reqEntity.addPart("myFile", fb);

if(params != null){

Iterator it = params.keySet().iterator();

while(it.hasNext()){

String name = it.next();

reqEntity.addPart(name, new StringBody(params.get(name),Charset.forName("UTF-8")));

}

}

httpPost.setEntity(reqEntity);

return invoke(httpPost);

} catch (Exception e) {

Log.e(TAG, e.toString());

}

return null;

}

参考网页:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值