c 调用java的webapi,使用Java HttpComponent/HttpClinet 调用 WebAPI问题的解决

几个关键字:

WebAPI, Android, Apache HttpComponent/HttpClient

问题:无论怎么测试, WebAPI的FormBody value总是空.

最简单的代码 WebAPI, 没有加认证

1 //POST api/

2 [HttpPost]3 public string Post([FromBody]stringvalue)4 {5 string val =value;6

7 Debug.WriteLine(value);8

9 returnvalue;10 }

最简单的代码, Java端,用StringEntity

1 public static void NotAuthTestPost() throwsIOException {2 CloseableHttpClient httpclient =HttpClients.createDefault();3 try{4 HttpPost hp = new HttpPost("http://localhost:8888/api/test");5

6 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}]}";7 8 StringEntity se = new StringEntity(str, ContentType.create("application/json", "UTF-8"));9 hp.setEntity(se);10

11 System.out.println(EntityUtils.toString(se));12

13 CloseableHttpResponse response1 = null;14 try{15 response1 =httpclient.execute(hp);16

17 System.out.println(response1.getStatusLine());18 HttpEntity entity1 =response1.getEntity();19

20 //do something useful with the response body21 //and ensure it is fully consumed22 //EntityUtils.consume(entity1);

23

24 String jsonstr =EntityUtils.toString(entity1);25

26 System.out.println(jsonstr);27

28 } catch(ClientProtocolException e) {29 e.printStackTrace();30 } catch(IOException e) {31 e.printStackTrace();32 } finally{33 response1.close();34 }35

36 } finally{37 httpclient.close();38 }39 }

结果:

9aa85726524b03ced8085f9bd0222c06.png

但是同样的Json, 使用C#的HTTPClient就完全没有问题.

计较了一下fiddle抓图:

使用C# HttpClient: (value是能取到)

80429092d6b3b7aa5a9118da302e0139.png

使用Java Apache HttpClient (Value取不到)

81728c56dc321638d18f9a402e1757d1.png

比较一下就发现, 在Raw视图, 才可以看出, HttpRequest的Body是有不同的. 就是一对引号. "".

所以把Java的代码中加一行:

str ="\"" +str + "\"";

WebAPI端就正常拿到Value了.

估计有更深层次的解决方案, 暂且先记一笔.

原文:http://www.cnblogs.com/tekikesyo/p/4500271.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值