java发送xml post请求(2)

借助于org.apache.commons.httpclient对象

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;

public class HttpPostXML {
	
	/**
	 * 发送xml数据请求到server端
	 * @param url xml请求数据地址
	 * @param xmlString 发送的xml数据流
	 * @return null发送失败,否则返回响应内容
	 */
	public static String post(String url,String xmlString){
		//关闭合同谈判
		System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); 
		System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true"); 
		System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "stdout");
		
		HttpClient client = new HttpClient();
		PostMethod myPost = new PostMethod(url);
		client.getParams().setSoTimeout(300*1000);
		String responseString = null;
		try{
			myPost.setRequestEntity(new StringRequestEntity(xmlString,"text/xml","utf-8"));
			int statusCode = client.executeMethod(myPost);
			if(statusCode == HttpStatus.SC_OK){
				BufferedInputStream bis = new BufferedInputStream(myPost.getResponseBodyAsStream());
				byte[] bytes = new byte[1024];
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				int count = 0;
				while((count = bis.read(bytes))!= -1){
					bos.write(bytes, 0, count);
				}
				byte[] strByte = bos.toByteArray();
				responseString = new String(strByte,0,strByte.length,"utf-8");
				bos.close();
				bis.close();
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		myPost.releaseConnection();
		client.getHttpConnectionManager().closeIdleConnections(0);
		return responseString;
	}
}

和上篇文字相比,指示对象稍有不同

你可能感兴趣的:(java,exception,xml,String,url,byte)