Http发送XML

注意:
1 发送xml数据给服务器,并非以请求参数方式发送,而是以实体数据,类型为字节数组
2 既然以实体数据发送就必须要采用POST方式即conn.setRequestMethod("POST");
3 必须要设置Content-Type和Content-Length这两个属性
4 利用OutputStream outStream = conn.getOutputStream();outStream.write(entity);发送实体数据
5 需要对<?xml version="1.0" encoding="utf-8"?>进行转义

代码如下:

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class SendXML {
	public static void main(String[] args) throws Exception {
		//转义!!!
		String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><videos><video><title>中国</title></video></videos>";
		String path = "http://192.168.1.100:8080/videoweb/video/manage.do?method=getXML";		
		byte[] entity = xml.getBytes("UTF-8");
		HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("POST");
		conn.setDoOutput(true);
		conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
		conn.setRequestProperty("Content-Length", String.valueOf(entity.length));
		OutputStream outStream = conn.getOutputStream();
		outStream.write(entity);
		if(conn.getResponseCode() == 200){
			System.out.println("success");
		}else{
			System.out.println("fail");
		}
	}

}


 

你可能感兴趣的:(Http发送XML)