.net调用java接口_C# .Net 调用Java接口 Java api Post Json 格式字符串

本文介绍了两种在C# .NET中调用Java接口的方法,通过POST发送JSON格式的数据。方法一是使用HttpWebRequest,创建POST请求,设置Content-Type为application/json,并将JSON数据写入请求流。方法二是利用HttpClient类,同样设置Content-Type并发送POST请求。
摘要由CSDN通过智能技术生成

用到的命名空间  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;

}

方法二:

/* url:POST请求地址

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

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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值