Java – 利用 HttpClient 執行 Http 請求
by GDX on 十二月.10, 2009, under Java, 程式設計
網路上有很多 Java 的 Http 相關 Library
這裡選用 HttpClient 的原因是 Google 的 Android 系統裡用的就是 HttpClient
如此一舉兩得,何樂而不為XD
HttpClient是需要另外下載的 Library,首先先到 http://hc.apache.org/下載 HttpClient 和 HttpCore 解開來加到專案中
如此就可以使用 HttpClient 來執行 Http 請求囉,以下為簡單的 HttpGet 範例
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://localhost/");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
int l;
byte[] tmp = new byte[2048];
while ((l = instream.read(tmp)) != -1) {
}
}
補充:
若是在 compile 的時候 compilier 說找不到 net.jcip.annotations.GuardedBy
到 http://jcip.net/ 下載 jcip-annotation.jar 就可以解決
補充2:
compile 時找不到
org.apache.common.logging
到 這裡下載 Logging