import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HttpXmlUtil {
private String method = "POST";
private String charset = "UTF-8";
private String contentType = "text/xml";
public String sendXmlMsg(String address, String xmlMsg) throws Exception {
StringBuilder sb = new StringBuilder();
URL url = new URL(address);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(method);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(true);
conn.setRequestProperty("Content-Type", contentType);
conn.connect();
// 向输出流写出数据
PrintWriter pw = new PrintWriter(conn.getOutputStream());
pw.write(xmlMsg);
pw.flush();
pw.close();
String contentType = conn.getContentType();
Pattern pattern = Pattern.compile("charset=.*:?");
Matcher matcher = pattern.matcher(contentType);
if (matcher.find()) {
charset = matcher.group();
if (charset.endsWith(";")) {
charset = charset.substring(charset.indexOf("=") + 1, charset.indexOf(";"));
} else {
charset = charset.substring(charset.indexOf("=") + 1);
}
if (charset.contains("\"")) {
charset = charset.substring(1, charset.length() - 1);
}
charset = charset.trim();
}
InputStream inStream = conn.getInputStream();
BufferedReader ufferedReader = new BufferedReader(new InputStreamReader(inStream, charset));
String line;
while ((line = ufferedReader.readLine()) != null) {
sb.append(line);
}
ufferedReader.close();
conn.disconnect();
return sb.toString();
}
}
Http发送xml
猜你喜欢
转载自blog.csdn.net/tangmingxin0529/article/details/80834879
今日推荐
周排行