国产一级a片免费看高清,亚洲熟女中文字幕在线视频,黄三级高清在线播放,免费黄色视频在线看

打開APP
userphoto
未登錄

開通VIP,暢享免費電子書等14項超值服

開通VIP
Android調(diào)用WebAPI之傳參、文件

最近把后臺改成 WebAPI ,客戶端向后臺傳參數(shù)、文件時碰到些問題:

一、傳參數(shù)

用 JQuery ajax 調(diào)用后臺方法時,后臺方法一般定義成這樣:

        [WebMethod]        [Authorize]        public string GetCustomList(string CustomerName, string Name, string Loc_Name, string selectStorageState)        {                   }

前臺這樣調(diào)用:

            $.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<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();            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<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();        nameValuePairs.add(new  BasicNameValuePair("", jsonString));String resultString= HttpHelper.invokePost("GetStockList", nameValuePairs);

二、傳文件

WebAPI 后臺

        [Authorize]        public Task<HttpResponseMessage> 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.            // 讀取表單數(shù)據(jù),并返回一個async任務(wù)            string sName = "88";            string nName = "";            string FilePath = "Uploads/";            Request.Content.Headers.ContentType.CharSet = "UTF-8";            var task = Request.Content.ReadAsMultipartAsync(provider).                ContinueWith<HttpResponseMessage>(t =>                {                     sName = provider.FileData[0].LocalFileName;                    string GpsImgJson = provider.FormData["GpsImgJson"];                    GpsImgJson = HttpUtility.UrlDecode(GpsImgJson, Encoding.GetEncoding("UTF-8"));                                       GpsImg gpsImg = JsonHelper.JsonDeserialize<GpsImg>(GpsImgJson);                    nName = gpsImg.FileName;                    FilePath += nName;                                        if (!File.Exists(root + "/" + FilePath))                    {                        File.Move(sName, root + "/" + FilePath);                    }                                    //保存                                        if (true)                    {                        return Request.CreateResponse<string>(HttpStatusCode.OK, "上傳成功");                    }                    else                    {                        return Request.CreateResponse<string>(HttpStatusCode.InternalServerError, "保存出錯!");                    }                                    });                      return task;        }

Android 前臺

String jsonString = "{\"Title\":\""+myTitleText.getText().toString()+                                    "\",\"Content\":\""+myContentText.getText().toString()+                                    "\",\"FileName\":\""+filename+                                    "\",\"Longitude\":\""+lonString+"\",\"Latitude\":\""+latString+"\"}";                            Map<String, String> params0 = new HashMap<String, String>();                            params0.put("GpsImgJson", jsonString);                            String st= HttpHelper.invokePost("AddImg", mImageUri.getPath(), params0);
public static String invokePost(String action, String filePath, Map<String, String> 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<String> 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;    }

參考網(wǎng)頁:

http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/

http://www.asp.net/web-api

本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊舉報
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
Android 如何收集已發(fā)布程序的崩潰信息
Android上如何正確實現(xiàn)程序的聯(lián)網(wǎng) 事關(guān)WIFI/CMWAP/CMNET
7.1.4 Android HTTP請求方式:HttpClient 
Android獲取網(wǎng)頁數(shù)據(jù)的方法總結(jié)
HttpClient在HTTP協(xié)議接口測試中的使用
Android http請求數(shù)據(jù) 設(shè)置超時
更多類似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長圖 關(guān)注 下載文章
綁定賬號成功
后續(xù)可登錄賬號暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點擊這里聯(lián)系客服!

聯(lián)系客服