C#中调用Servlet示例
需求
通用消息接口使用servlet作为服务器端服务接口,第三方应用程序通过http post的方式调用servlet,实现与通用消息接口的调用连接。
参数说明如下:
msgtitle:消息标题,描述发送消息的标题
serviceid:服务编号,消息的服务编号
msgdesp:消息描述,消息的详细内容
msgurl:url地址,消息中包含的 url
上述4个参数的参数值可以为空,但参数必须提供。
调用示例
下面一段简单的html代码,描述了如何通过网页进行调用通用消息接口的模式,供参考。
<html><head><title>sametime通用消息服务</title>
</head><body>
<formaction="http://stproxy.test.foton.com:9080/
fotonstbot/serviceservlet" method="post">name="msgtitle" /><br />
服务编号: <input type="text" id="serviceid" name="serviceid" /><br />
消息描述: <input type="text" id="msgdesp" name="msgdesp" /><br />
url: <input type="text" id="msgurl" name="msgurl" /><br />
系统类型: <input type="text" id="systype" name="systype" /><br />
目标用户: <input type="text" id="targetuser" name="targetuser" style="width:500px;" /><br />
<input type="submit" value="submit" />
</form>
</body></html>
c#调用示例
/// <summary>
/// sametime
/// </summary>
/// <param name="bstrreceiver">sametime用户</param>
/// <param name="bstrtitle">标题</param>
/// <param name="ldelaytime">响应时间</param>
/// <param name="bstrmsg">内容</param>
public static void sendnotify(string bstrreceiver, string bstrtitle, int ldelaytime, string bstrmsg)
{
string user="";
try {
string url = "http://stproxy.foton.com.cn:9081/fotonstbot/serviceservlet";//html调用的地址
httpwebrequest webrequest = (httpwebrequest)webrequest.create(url);
if(webrequest==null)
{
recordererrorrtx(bstrreceiver,bstrtitle,bstrmsg,"服务端异常",0);
return;
}
webrequest.method = "post";
webrequest.timeout = ldelaytime;
webrequest.contenttype = "application/x-www-form-urlencoded";
byte[] buffertitile = encoding.getencoding("utf-8").getbytes(bstrtitle);
string sbtitle = "";
foreach (byte b in buffertitile) sbtitle=sbtitle+(string.format("%{0:x}", b));
byte[] buffercontent = encoding.getencoding("utf-8").getbytes(bstrmsg);
string sbcontent = "";
//utf8注意转码
foreach (byte b in buffercontent) sbcontent=sbcontent+(string.format("%{0:x}", b));
system.collections.hashtable pars=new system.collections.hashtable();
pars.add("msgtitle", sbtitle);
pars.add("serviceid", "");
pars.add("msgdesp", sbcontent);
pars.add("msgurl", "");
pars.add("systype", "qcts");
user="uid="+bstrreceiver+",cn=users,dc=foton;";
pars.add("targetuser", user);
string buffer="";
//发送post数据
if (!(pars == null || pars.count == 0))
{
foreach (string key in pars.keys)
{
buffer=buffer+"&"+key+"="+pars[key].tostring();
}
byte[] data = encoding.utf8.getbytes(buffer);
using (stream stream = webrequest.getrequeststream())
{
stream.write(data, 0, data.length);
}
}
string[] values = webrequest.headers.getvalues("content-type");
webresponse myresponse= webrequest.getresponse();
using(stream resstream = myresponse.getresponsestream())//得到回写的流
{
streamreader newreader = new streamreader(myresponse.getresponsestream(), encoding.utf8);
string content = newreader.readtoend();
newreader.close();
}
recorderrtx(user,bstrtitle,bstrmsg,0);
}
catch(exception ex)
{
recordererrorrtx(user,bstrtitle,bstrmsg,ex.message,0);
}
}