首页 新闻 会员 周边

Java Post调用C#的webapi问题

0
悬赏园豆:30 [已解决问题] 解决于 2015-07-23 08:18

开发项目过程中别组的同事用java调用我们的接口,接口是api形式的,上代码

 [HttpPost]
 public LpdReturnDto Post([FromBody]UserAppend value)
{
     return new LpdReturnDto();
}
UserAppend 为定义的一个类

他们调用的时候Post过来始终接收不到参数value的值。

有谁用过java调用webapi的吗?这样写有啥问题没有。

使用jquery的ajax调用没有问题

var d={"age":1};
$.ajax({
        url: "http://localhost:60736/api/User",
        type: "POST",
        data: (d),
        success: function (data) {
            alert("post:" + data.status);
        }
});
问题补充:

 

目前找到一个解决方法

byte[] byts = new byte[HttpContext.Current.Request.InputStream.Length];
HttpContext.Current.Request.InputStream.Read(byts, 0, byts.Length);
string req = System.Text.Encoding.Default.GetString(byts);

最终获得的req就是post过来的值。

不知道还有没有更好的方法。

webaspx的主页 webaspx | 小虾三级 | 园豆:1973
提问于:2015-07-22 14:01
< >
分享
最佳答案
0

用Wireshark抓包看一下Java发过来的请求内容是什么?问题可能出在Java调用代码上

收获园豆:15
dudu | 高人七级 |园豆:31003 | 2015-07-22 14:16

谢谢,不过这玩意不会用。

webaspx | 园豆:1973 (小虾三级) | 2015-07-22 14:47

@webaspx: Java调用代码的问题,传的是json,应该用application/json,而不是application/x-www-form-urlencoded。

dudu | 园豆:31003 (高人七级) | 2015-07-22 16:18

@dudu: 嗯,我现在在用jQuery模拟Java的调用传Json过来,但是未成功。

webaspx | 园豆:1973 (小虾三级) | 2015-07-22 16:31

@webaspx: $.ajax中要加上

contentType:"application/json; charset=utf-8"
dudu | 园豆:31003 (高人七级) | 2015-07-22 16:33

@dudu: 

    $.ajax({
        url: "http://localhost:60736/api/User",
        type: "POST",
        dataType: 'json',
        contentType: 'application/json;charset=utf-8',
        data: JSON.stringify(d) ,
        success: function (data) {
            alert("post:" + data.status);
        }
    });

加上了,后台还是接收不到

webaspx | 园豆:1973 (小虾三级) | 2015-07-22 16:35

@webaspx: 不用value,换一个参数名称试试

dudu | 园豆:31003 (高人七级) | 2015-07-22 16:45

@dudu: 还是不行。是否需要修改后台代码?

webaspx | 园豆:1973 (小虾三级) | 2015-07-22 16:57

@webaspx: ASP.NET Web API的版本是多少?

dudu | 园豆:31003 (高人七级) | 2015-07-22 17:05

@dudu: Microsoft.AspNet.WebApi.Core.5.2.3

webaspx | 园豆:1973 (小虾三级) | 2015-07-22 17:07

@webaspx: 我们也是这样使用Web API的,没遇到这个问题。

dudu | 园豆:31003 (高人七级) | 2015-07-22 17:18

@webaspx: 谢谢dudu,目前找到一个方法就流中读取。不知道有没有更好的方法处理。期待·~

webaspx | 园豆:1973 (小虾三级) | 2015-07-22 17:18

@webaspx: 应该有更好的处理方法,UserAppend是如何定义的?

dudu | 园豆:31003 (高人七级) | 2015-07-23 09:40

@dudu: 就是一个普通的类定义

webaspx | 园豆:1973 (小虾三级) | 2015-07-23 09:45

@webaspx: 如果可以的话,提供一个能够重现这个问题的示例代码项目,我这边测试一下。

dudu | 园豆:31003 (高人七级) | 2015-07-23 09:46

@dudu: 当然可以,一会发给您

webaspx | 园豆:1973 (小虾三级) | 2015-07-23 09:49

@dudu: http://files.cnblogs.com/files/lvcao2099/WebapiDemo.7z 

Demo已上传,您可以试试。

webaspx | 园豆:1973 (小虾三级) | 2015-07-23 10:51

@webaspx: 收到,我试一下

dudu | 园豆:31003 (高人七级) | 2015-07-23 10:55

@dudu: 晕死,刚把UserAppend上的[Serializable]标记给注释了就行了。

webaspx | 园豆:1973 (小虾三级) | 2015-07-23 10:57

@dudu: 题外的问题,这是bug?

webaspx | 园豆:1973 (小虾三级) | 2015-07-23 11:01

@webaspx: 我之前也怀疑到这个地方了,但是不确定,准备自己测试时试一下的。

dudu | 园豆:31003 (高人七级) | 2015-07-23 11:01

@dudu: 好吧,不知道当时鬼使神差的就加上了那个标记了。

webaspx | 园豆:1973 (小虾三级) | 2015-07-23 11:02

@webaspx: 我先记一下,应该是bug

dudu | 园豆:31003 (高人七级) | 2015-07-23 11:03

@dudu: 谢谢dudu老大,终于解决问题了

webaspx | 园豆:1973 (小虾三级) | 2015-07-23 11:05
其他回答(2)
0

可以明确的说就是调用的不会调...

我这边也有个同时做安卓的.不会调接口就说你接口做的有问题.o(︶︿︶)o 唉

收获园豆:5
吴瑞祥 | 园豆:29449 (高人七级) | 2015-07-22 15:25

@webaspx  看出问题了.是java的请求头正文格式不匹配

传输的是json格式,但是头里面确写form格式,webapi自然就解析不了

支持(0) 反对(0) 吴瑞祥 | 园豆:29449 (高人七级) | 2015-07-22 18:02

@吴瑞祥: 用jQuery测试,改成 contentType: 'application/json;charset=utf-8' 也是一样接收不到值。

支持(0) 反对(0) webaspx | 园豆:1973 (小虾三级) | 2015-07-23 08:21

@webaspx: 当然啦.因为jquery不是用json请求的啊.

支持(0) 反对(0) 吴瑞祥 | 园豆:29449 (高人七级) | 2015-07-23 12:35
0

抓包看一下java和ajax请求的差异在哪儿~

收获园豆:10
幻天芒 | 园豆:37175 (高人七级) | 2015-07-22 16:04

抓到不同了,Java掉用的时候是Json格式过来的,所以没接收到。

支持(0) 反对(0) webaspx | 园豆:1973 (小虾三级) | 2015-07-22 16:13

@webaspx: 那这就好解决啦,哈哈~话说Fiddle就可以抓了~

支持(0) 反对(0) 幻天芒 | 园豆:37175 (高人七级) | 2015-07-22 16:17

@幻天芒: 小弟现在头晕的不行,请赐教如何解决这问题?

支持(0) 反对(0) webaspx | 园豆:1973 (小虾三级) | 2015-07-22 16:30

@webaspx: http://ithelp.ithome.com.tw/question/10137046 看下这篇文章。自定义ValueProviderFactory 来解析json格式的请求。

支持(0) 反对(0) 幻天芒 | 园豆:37175 (高人七级) | 2015-07-23 09:39

@幻天芒: 网页无法打开

支持(0) 反对(0) webaspx | 园豆:1973 (小虾三级) | 2015-07-23 09:46

@webaspx: 

  1. public class JsonNetValueProviderFactory : ValueProviderFactory  
  2. {  
  3.     public override IValueProvider GetValueProvider(ControllerContext controllerContext)  
  4.     {  
  5.         // first make sure we have a valid context  
  6.         if (controllerContext == null)  
  7.             throw new ArgumentNullException("controllerContext");  
  8.   
  9.         // now make sure we are dealing with a json request  
  10.         if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))  
  11.             return null;  
  12.   
  13.         // use JSON.NET to deserialize object to a dynamic (expando) object  
  14.         Object JSONObject;  
  15.   
  16.         // get a generic stream reader (get reader for the http stream)  
  17.         using (StreamReader streamReader = new StreamReader(controllerContext.HttpContext.Request.InputStream))  
  18.         {  
  19.             // convert stream reader to a JSON Text Reader  
  20.             using (JsonTextReader JSONReader = new JsonTextReader(streamReader))  
  21.             {  
  22.                 // tell JSON to read  
  23.                 if (!JSONReader.Read())  
  24.                     return null;  
  25.   
  26.                 // make a new Json serializer  
  27.                 JsonSerializer JSONSerializer = new JsonSerializer();  
  28.                 // add the dyamic object converter to our serializer  
  29.                 JSONSerializer.Converters.Add(new ExpandoObjectConverter());  
  30.   
  31.                 // if we start with a "[", treat this as an array  
  32.                 if (JSONReader.TokenType == JsonToken.StartArray)  
  33.                     JSONObject = JSONSerializer.Deserialize<List<ExpandoObject>>(JSONReader);  
  34.                 else  
  35.                     JSONObject = JSONSerializer.Deserialize<ExpandoObject>(JSONReader);  
  36.             }  
  37.         }  
  38.   
  39.         // create a backing store to hold all properties for this deserialization  
  40.         Dictionary<string, object> backingStore = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);  
  41.         // add all properties to this backing store  
  42.         AddToBackingStore(backingStore, String.Empty, JSONObject);                  
  43.   
  44.         // return the object in a dictionary value provider so the MVC understands it  
  45.         return new DictionaryValueProvider<object>(backingStore, CultureInfo.CurrentCulture);  
  46.     }  
  47.   
  48.     private static void AddToBackingStore(Dictionary<string, object> backingStore, string prefix, object value)  
  49.     {  
  50.         IDictionary<string, object> d = value as IDictionary<string, object>;  
  51.         if (d != null)  
  52.         {  
  53.             foreach (KeyValuePair<string, object> entry in d)  
  54.             {  
  55.                 AddToBackingStore(backingStore, MakePropertyKey(prefix, entry.Key), entry.Value);  
  56.             }  
  57.             return;  
  58.         }  
  59.   
  60.         IList l = value as IList;  
  61.         if (l != null)  
  62.         {  
  63.             for (int i = 0; i < l.Count; i++)  
  64.             {  
  65.                 AddToBackingStore(backingStore, MakeArrayKey(prefix, i), l[i]);  
  66.             }  
  67.             return;  
  68.         }  
  69.   
  70.         backingStore[prefix] = value;  
  71.     }  
  72.   
  73.     private static string MakeArrayKey(string prefix, int index)  
  74.     {  
  75.         return prefix + "[" + index.ToString(CultureInfo.InvariantCulture) + "]";  
  76.     }  
  77.   
  78.     private static string MakePropertyKey(string prefix, string propertyName)  
  79.     {  
  80.         return (String.IsNullOrEmpty(prefix)) ? propertyName : prefix + "." + propertyName;  
  81.     }  
  82. }  


2. 在App_Start建立ValueProviderConfig,註冊ValueProviderFactory

  1. public class ValueProviderConfig  
  2. {  
  3.     public static void Initialize()  
  4.     {  
  5.         ValueProviderFactories.Factories.Remove(ValueProviderFactories.Factories  
  6.                                                                       .OfType<JsonValueProviderFactory>()  
  7.                                                                       .FirstOrDefault());  
  8.         ValueProviderFactories.Factories.Add(new JsonNetValueProviderFactory());  
  9.     }  
  10. }  


3. 在Global.asax加入啟動

  1. ValueProviderConfig.Initialize();  
支持(0) 反对(0) 幻天芒 | 园豆:37175 (高人七级) | 2015-07-23 09:47

@幻天芒: 谢谢,一会试试。

支持(0) 反对(0) webaspx | 园豆:1973 (小虾三级) | 2015-07-23 09:52
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册