
几个关键字:
WebAPI, Android, Apache HttpComponent/HttpClient
问题:无论怎么测试, WebAPI的FormBody value总是空.
最简单的代码 WebAPI, 没有加认证
// POST api/<controller>
[HttpPost]
public string Post([FromBody]string value)
{
string val = value; Debug.WriteLine(value); return value;
}
最简单的代码, Java端,用StringEntity
public static void NotAuthTestPost() throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost hp = new HttpPost("http://localhost:8888/api/test"); String str="{'Header':[{'summary':111,'endtime':570,'end_date':1431381600,'resid':'sc20150512034635','starttime':570,'scheduleid':'sc155485e5025f3d','machid':'sc155485e8044b93','parentid':null,'start_date':1431381600}],'Detail':[{'perm_modify':1,'owner':1,'perm_delete':1,'resid':'sc20150512034635','memberid':'sc1555070e4d8217','invited':0},{'perm_modify':0,'owner':0,'perm_delete':0,'resid':'sc20150512034635','memberid':'sc155489a07e0e24','invited':1}]}";
StringEntity se = new StringEntity(str, ContentType.create("application/json", "UTF-8"));
hp.setEntity(se); System.out.println(EntityUtils.toString(se)); CloseableHttpResponse response1 = null;
try {
response1 = httpclient.execute(hp); System.out.println(response1.getStatusLine());
HttpEntity entity1 = response1.getEntity(); // do something useful with the response body
// and ensure it is fully consumed
// EntityUtils.consume(entity1); String jsonstr = EntityUtils.toString(entity1); System.out.println(jsonstr); } catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
response1.close();
} } finally {
httpclient.close();
}
}
结果:
但是同样的Json, 使用C#的HTTPClient就完全没有问题.
计较了一下fiddle抓图:
使用C# HttpClient: (value是能取到)
使用Java Apache HttpClient (Value取不到)
比较一下就发现, 在Raw视图, 才可以看出, HttpRequest的Body是有不同的. 就是一对引号. "".
所以把Java的代码中加一行:
str ="\"" +str + "\"";
WebAPI端就正常拿到Value了.
估计有更深层次的解决方案, 暂且先记一笔.
>>2015/06/15
把WebAPI的参数value的类型改为object就可以了. 这么狗血的解决方案.