以下列出幾個常用的.
1. Add Headers
GetMethod method = new GetMethod();
method.addRequestHeader("headerName", "headerValue");
// or
method.addRequestHeader(new Header("headerName", "headerValue"));
2. 設定 timeout 時間
HttpMethodParams params = new HttpMethodParams();
params.setSoTimeout(3000);
// or
method.getParams().setSoTimeout(3000);
3. 多執行序下使用 HttpClient
HttpClient client = new HttpClient(new MultiThreadedHttpConnectionManager());
// or
MultiThreadedHttpConnectionManager config = new MultiThreadedHttpConnectionManager());
// set other config
HttpClient client = new HttpClient();
client.setHttpConnectionManager(config);
補充: 如果您的程式會一直使用 httpclient 發送 request, 建意將 httpclient 宣告成只有一份(ex: static or singleton), 減少不必要要的 port 被開啟, 又要等待 system close.
4. 失敗時, retry 3 次
// set per default
client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler());
// or
DefaultMethodRetryHandler retryhandler = new DefaultMethodRetryHandler(10, true);
client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryhandler);
// 如果想了解哪些情況下, 才會 retry, 請參考官網 http://hc.apache.org/httpclient-3.x/tutorial.html
目前這些囉, 有想到什麼常用的到時候再補充唷.
0 意見:
張貼留言