记录:C# 调用 java api
最近写个项目,是提供接口的项目,项目使用java编写的,但是客户需要用C# 调用这套接口,一开始我没太关注,因为postman都正常调用,但是在写C# 调用Demo时出现问题了。public static void Test(){string result = DoPost("http://ip:port/user/login", Prepar...
·
最近写个项目,是提供接口的项目,项目使用java编写的,但是客户需要用C# 调用这套接口,一开始我没太关注,因为postman都正常调用,但是在写C# 调用Demo时出现问题了。
public static void Test()
{
string result = DoPost("http://ip:port/user/login", PreparationParameters());
}
private static Dictionary<string, object> PreparationParameters()
{
return new Dictionary<string, object>()
{
{ "username","test"},
{ "secret", "test"}
};
}
private static string DoPost(string url, object param)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "*/*";
request.ContentType = "application/json";
//request.Timeout = Timeout.Infinite;
request.Timeout = 80000;
request.Method = "Post";
request.Proxy = null;
string json = JsonConvert.SerializeObject(param);
byte[] data = Encoding.UTF8.GetBytes(json);
request.ContentLength = data.Length;
using(Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
stream.Flush();
}
using (StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream()))
{
string result = reader.ReadToEnd();
return result;
}
}
如上图显示,出现问题是我传递的参数总是为空,也就是我C# 传递的参数,java接收不到,一开始考虑的是不是ContentType的问题,换了别的还是参数传递不过去,没办法,我用java代码测试了一下
public static String Post(String URL, Map<String, Object> parameter){
try{
return HttpRequest.post(URL)
.form(parameter).timeout(20000).execute().body();
}catch (Exception ex){
return String.format("异常:{0}", ex.getMessage());
}
}
神奇的是java这样传递的话,接口能够正常接收到参数,并且正常调用.
public static void Test()
{
string result = DoPost("http://ip:port/user/login", PreparationParameters());
}
private static NameValueCollection PreparationParameters()
{
return new NameValueCollection
{
{ "username", "test" },
{ "secret", "test" }
};
}
private static string DoPost(string url, NameValueCollection param)
{
using (WebClient webClient = new WebClient())
{
try
{
byte[] remoteInfo = webClient.UploadValues(url, "POST", param);
string result = Encoding.UTF8.GetString(remoteInfo);
return result;
}
catch (Exception ex)
{
return ex.Message;
}
}
}
最后代码改成这个样子,可以了,能够正常调用了,但是个中原委,还是不太清楚,这次记录一下,有机会再研究吧
更多推荐
已为社区贡献2条内容
所有评论(0)