用PostMan向服务器发了Post请求,返回是以下的Json.
用HttpClient组件发送请求并接收返回,代码如下:
httpClient = new HttpClient(); httpClient.BaseAddress = new Uri(BaseUri); httpClient.DefaultRequestHeaders.Add("Accept", "application/json"); HttpContent postContent = new FormUrlEncodedContent(dicPara); var response = await httpClient.PostAsync("v1/goods", postContent); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsStringAsync(); }
接收到的数据却是:
data里的对象是{}.
我用HttpWebRequest却又能正常:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.CookieContainer = new CookieContainer(); CookieContainer cookie = request.CookieContainer;//如果用不到Cookie,删去即可 //以下是发送的http头,随便加,其中referer挺重要的,有些网站会根据这个来反盗链 request.Referer = ""; request.Accept = "Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; request.Headers["Accept-Language"] = "zh-CN,zh;q=0."; request.Headers["Accept-Charset"] = "GBK,utf-8;q=0.7,*;q=0.3"; request.UserAgent = "User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1"; request.KeepAlive = true; //上面的http头看情况而定,但是下面俩必须加 request.ContentType = "application/x-www-form-urlencoded"; request.Method = "POST"; Encoding encoding = Encoding.UTF8;//根据网站的编码自定义 byte[] postData = encoding.GetBytes(postDataStr);//postDataStr即为发送的数据,格式还是和上次说的一样 request.ContentLength = postData.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(postData, 0, postData.Length); HttpWebResponse response = null; try { response = (HttpWebResponse)request.GetResponse(); }
虽说HttpWebResponse可以,但我想用HttpClient的异步方法取出数据,有什么方法呢?
明明是你的写法有问题。第一种方式,你明明指定了用json格式提交了,你还用FormUrlEncodedContent格式干嘛。
请问要如何写呢,第一种方法,我没写json格式提交也不行?
@秋官: 你们的服务器好像不支持form提交吧,你只能用json提交。把json字符串放到StringEntity里面,然后用HttpPost的setEntity(StringEntity);吧。
using (var httpClient = new HttpClient()) { var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "datacool_winform", "27C68F9A899842A598DDBACD2806FDD7"))); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials); string url = "http://" + MiddlewareIP + ":5990" + "/api/CloudPOS/GetVersion?k=" + Guid.NewGuid().ToString(); try { string requestResult = httpClient.GetStringAsync(url).Result; return requestResult; } catch (Exception ex) { Com.DataCool.DotNetExpand.LogHelper.Error(ex); return string.Empty; } }
换成同步的方式试试,感觉写法上有点问题。但是不确定