发送XML给第三方
面试中有一个题目是发送(接受)xml,并解析。
当时有接触但是没有注意,所以回来强力关注下,并且记录在这,大家一起学习下:
[java]
public static StringBuffer sendSoapMsg(String soapMessage,
String targetUrl, String soapAction, Long timeout) throws Exception
{
busLogger.enterFuncDebugLog(soapMessage, soapAction, targetUrl, timeout);
//保存响应消息
HttpURLConnection conn = null;
BufferedReader bf = null;
StringBuffer sb = new StringBuffer();
try
{
URL url = new URL(targetUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.addRequestProperty("SOAPAction", soapAction);
conn.addRequestProperty("Content-type", "text/xml; charset=UTF-8");
//默认超时时间30秒
conn.setConnectTimeout(timeout.intValue());
//将发送请求参数写入到http请求中
conn.getOutputStream().write(soapMessage.getBytes());
conn.getOutputStream().flush();
conn.getOutputStream().close();
//从服务器获取响应结果
InputStream in = conn.getInputStream();
//从服务器读取结果
bf = new BufferedReader(new InputStreamReader(in));
String s = null;
while ((s = bf.readLine()) != null)
{
sb.append(s);
}
}
catch (Exception e)
{
busLogger.excepFuncDebugLog(e);
throw e;
}
finally
{
if (null != bf)
{
try
{
bf.close();
}
catch (IOException e)
{
busLogger.excepFuncDebugLog(e);
}
}
if (conn != null)
{
conn.disconnect();
}
}
busLogger.exitFuncDebugLog(sb.toString());
return sb;
}
public static StringBuffer sendSoapMsg(String soapMessage,
String targetUrl, String soapAction, Long timeout) throws Exception
{
busLogger.enterFuncDebugLog(soapMessage, soapAction, targetUrl, timeout);
//保存响应消息
HttpURLConnection conn = null;
BufferedReader bf = null;
StringBuffer sb = new StringBuffer();
try
{
URL url = new URL(targetUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.addRequestProperty("SOAPAction", soapAction);
conn.addRequestProperty("Content-type", "text/xml; charset=UTF-8");
//默认超时时间30秒
conn.setConnectTimeout(timeout.intValue());
//将发送请求参数写入到http请求中
补充:移动开发 , Android ,