使用Java HttpComponent/HttpClinet 调用 WebAPI问题的解决

几个关键字:

WebAPI, Android, Apache HttpComponent/HttpClient

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

 

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

 1 // POST api/<controller>
 2 [HttpPost]
 3 public string Post([FromBody]string value)
 4 {
 5     string val = value;
 6 
 7     Debug.WriteLine(value);
 8 
 9     return value;
10 }

 

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

 1     public static void NotAuthTestPost() throws IOException {
 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 body
21                 // and ensure it is fully consumed
22                 // 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     }

 

结果:

技术分享

 

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

计较了一下fiddle抓图:

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

技术分享

 

使用Java Apache HttpClient (Value取不到)

技术分享

 

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

 

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

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

 

WebAPI端就正常拿到Value了.

 

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

 

文章来自:http://www.cnblogs.com/tekikesyo/p/4500271.html
© 2021 jiaocheng.bubufx.com  联系我们
ICP备案:鲁ICP备09046678号-3