- 相關推薦
關于JAVA實現httpClient的實例
HttpClient 是 Apache Jakarta Common 下的子項目,可以用來提供高效的、最新的、功能豐富的支持 HTTP 協議的客戶端編程工具包,并且它支持 HTTP 協議最新的版本和建議。下面小編準備了關于JAVA實現httpClient的實例,提供給大家參考!
package net.xfok.http;
import java.util.HashMap; import java.util.Iterator; import java.util.Map;
import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod;
/**
*/
public class MyClient {
/**
*的到Http請求結果
* @param url請求地址
* @param parms請求參數
* @return
*/
public byte[] getBody(String url,Map parms){
byte[] body=null;
//構造HttpClient的實例
HttpClient httpClient = new HttpClient();
//創建GET方法的實例
PostMethod postMethod = new PostMethod(url);
//填入各個表單域的值
NameValuePair[] data = new NameValuePair[parms.keySet().size()]; Iterator it = parms.entrySet().iterator();
int i=0;
while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); Object key = entry.getKey(); Object value = entry.getValue(); data[i]=new NameValuePair(key.toString(),value.toString());
i++;
}
//將表單的值放入postMethod中
postMethod.setRequestBody(data);
try {
//執行postMethod
int statusCode = httpClient.executeMethod(postMethod); // HttpClient對于要求接受后繼服務的請求,象POST和PUT等不能自動處理轉發
// 301或者302
if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
//從頭中取出轉向的地址
Header locationHeader = postMethod
.getResponseHeader(“location”);
String location = null;
if (locationHeader != null) { location = locationHeader.getValue(); System.out .println(“The page was redirected to:” + location);
} else {
System.err.println(“Location field value is null.”);
}
}
body = postMethod.getResponseBody();
} catch (Exception e) {
e.printStackTrace();
}
return body;
}
public static void main(String[] args) {
String url=“http://www.xfok.net”;
Map parms=new HashMap();
MyClient client=new MyClient();
String result=new String(client.getBody(url, parms)); System.out.println(result);
}
}
【JAVA實現httpClient的實例】相關文章:
實現鼠標畫圖的Java程序06-22
Java多線程的實現方式07-08
PHP實現RSA加密類的實例解析10-25
Java動態代理實現AOP的方法07-22
Java如何實現簡單的whois查詢09-21
Java byte[]轉int如何實現05-24
Java語言的特點和實現機制10-01
使用JavaScript實現Java的List功能10-26
Java文件解壓縮實例詳解201607-26
java實現web服務器的方法10-14