透過Ant執行HttpMethod

使用分散式的持續整合系統,大都會面對透過http protocol存取所需資源。以內建或者必備的套件來說:

但HTTP PUT或HTTP DELETE呢? 有的人可能會想到CURL,但如果要做成好用的task,你可能需要花不少時間實作。本篇將會介紹Ant-Http的用法來減少大家的時間成本。

Get Artifacts

Ant-Http的原始碼可以從GitHub上取得,可以直接透過git從https://github.com/antlibs/ant-http.git clone。我是透過eclipse匯入的,因為它專案libraries是透過ivy resolve,所以整個在eclipse上跑起來沒什麼問題;build ant lib可以直接執行它提供的build.xml,以下是專案結構內容:


在設定上,dist有一個ant-http所提供的範例,所以應該不會有什麼問題。使用的部分我直接提供範例給大家參考。

HTTP PUT

PUT我用於上傳檔案。source file透過entity指定;如果你的http server需要basic認證,可以使用credentials。

	<target name="put-artifact">
		<http url="http://192.168.1.123/repositories/test_project/branch.properties" 
			method="PUT" printrequestheaders="true" expected="201">
		  	<entity file="branch.properties"/>
			<credentials username="admin" password="123456" show="true"/>
		</http>
	</target>
假如你要上傳的檔案非文字檔而是二進位檔,如執行檔、zip檔等,記得要在entity宣告binary為true:
<entity file="test.zip" binary="true"/>

HTTP DELETE

	<target name="delete-artifact">
		<http url="http://192.168.1.123/repositories/test_project/branch.properties" 
			method="DELETE" printrequestheaders="true" expected="204">
			<credentials username="admin" password="123456" show="true"/>
		</http>
	</target>

Others

預設ant-http會做status code的驗證,假如你不需要這個驗證,可以使用failOnUnexpected屬性:

<http url="http://192.168.1.123/repositories/test_project/branch.properties" 
			method="DELETE" printrequestheaders="true" failOnUnexpected="false"/>