HttpClient的Post請求數據


最近在項目中需要添加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"
           }
       ]
}

 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM