栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

.net调用java接口

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

.net调用java接口

用到的命名空间  using System.Net;

方法一:

//url:POST请求地址

//postData:json格式的请求报文,例如:{"key1":"value1","key2":"value2"}

public static string PostUrl(string url, string postData)

{

string result = "";

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

req.Method = "POST";

req.Timeout = 800000;//设置请求超时时间,单位为毫秒

req.ContentType = "application/json";

byte[] data = Encoding.UTF8.GetBytes(postData);

req.ContentLength = data.Length;

using (Stream reqStream = req.GetRequestStream())

{

reqStream.Write(data, 0, data.Length);

reqStream.Close();

}

HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

Stream stream = resp.GetResponseStream();

//获取响应内容

using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))

{

result = reader.ReadToEnd();

}

return result;

}

方法二:

public static string PostJson(string url, string postData)

{

string result = "";

System.Net.Http.HttpContent httpContent = new System.Net.Http.StringContent(postData);

httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

httpContent.Headers.ContentType.CharSet = "utf-8";

//string postUrl = "http://test.***.gov.cn:81**/request";

string postUrl = url;

if (postUrl.StartsWith("https"))

{

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;

}

System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();

try

{

System.Net.Http.HttpResponseMessage response = httpClient.PostAsync(postUrl, httpContent).Result;

//result = response.IsSuccessStatusCode?string.Empty:response.StatusCode.ToString();

result = response.Content.ReadAsStringAsync().Result;

}

catch(Exception ex)

{

result = ex.Message;

}

return result;

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/955423.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号