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;
	}
}

和上篇文字相比,指示對象稍有不同
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章