標籤:encode 指定 執行 response 回應標頭 static word 編寫 keyword
最近在項目中需要添加Post請求資料,以前的Get請求是使用JDK內建的URLConnection。在項目組人員的推薦下,開始使用HttpClient。
HttpClient簡介:
HttpClient是Apache Jakarta Common下的子項目,用來提供高效的、最新的、功能豐富的支援HTTP協議的用戶端編程工具包,
並且它支援HTTP協議最新的版本和建議。HttpClient已經應用在很多的項目中,比如Apache Jakarta上很著名的另外兩個開源項目Cactus
和HTMLUnit都使用了HttpClient。
HttpClient發送請求的步驟:
(1)建立HttpClient對象。
(2)建立要求方法的執行個體,並指定請求URL。如果需要發送GET請求,建立HttpGet對象;如果需要發送POST請求,建立HttpPost對象。
(3) 如果需要發送請求參數,可調用HttpGet、HttpPost共同的setParams(HetpParams params)方法來添加請求參數;對於HttpPost對象而言,
也可調用setEntity(HttpEntity entity)方法來佈建要求參數。
(4)調用HttpClient對象的execute(HttpUriRequest request)發送請求,該方法返回一個HttpResponse。
(5)調用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可擷取伺服器的回應標頭;調用HttpResponse的getEntity()方法
可擷取HttpEntity對象,該對象封裝了伺服器的響應內容。程式可通過該對象擷取伺服器的響應內容。
(6) 釋放串連。無論執行方法是否成功,都必須釋放串連
因此,接下來按照該步驟,編寫Post請求代碼如下:
public String doPost(String url, Map<String,String> map, String charset){
CloseableHttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try{
httpClient = HttpClients.createDefault();
httpPost = new HttpPost(url);
//設定參數
List<NameValuePair> list = new ArrayList<NameValuePair>();
Iterator iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<String,String> elem = (Map.Entry<String, String>) iterator.next();
list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
}
if(list.size() > 0){
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);
httpPost.setEntity(entity);
}
HttpResponse response = httpClient.execute(httpPost);
if(response != null){
HttpEntity resEntity = response.getEntity();
if(resEntity != null){
result = EntityUtils.toString(resEntity,charset);
}
}
}catch(Exception ex){
ex.printStackTrace();
}
return result;
}
測試代碼如下:
public static void main(String[] args) throws UnsupportedEncodingException {
String url = "http://admin.tingwen.me/index.php/api/interfaceXykj/touList";
Map<String,String> params = new HashMap<>();
params.put("page","100");
HttpClient client = new HttpClient();
String result = client.doPost(url,params,"UTF-8");
System.out.println(UnicodeToString(result));
}
測試結果:
{
"status": 1,
"msg": "查詢頭條新聞成功!",
"results": [
{
"id": "65678",
"tuiid": "0",
"post_author": "8909",
"post_news": "161",
"author": "0",
"post_keywords": "Snap,無人機,科技",
"post_date": "2017-03-03 16:19:43",
"post_times": "",
"post_content": "",
"post_title": "傳Snap公司正研發無人機:貫徹公司理念",
"post_lai": "新浪科技",
"post_mp": "http://mp3.tingwen.me/data/upload/mp3/58b9270c35694.mp3",
"post_time": "105000",
"post_size": "1268345"
}
]
}
HttpClient的Post請求資料