歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android中使用HttpClient的簡單例子

Android中使用HttpClient的簡單例子

日期:2017/3/1 11:12:42   编辑:Linux編程
Android中使用HttpClient的簡單例子:
  1. public boolean uploadHttpClient(String path, Map<String, String> params) throws IOException{
  2. //1.參數放進一個list集合當中,每個參數是一個NameValuePair對象
  3. List<NameValuePair> paramPair = new ArrayList<NameValuePair>();
  4. if(params != null && !params.isEmpty()){
  5. for(Map.Entry<String, String> entry : params.entrySet()){
  6. paramPair.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
  7. }
  8. }
  9. //2.創建請求實體對象,參數集合作為構造參數
  10. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramPair, "utf-8");
  11. //3.創建post請求,並把實體對象放進去
  12. HttpPost post = new HttpPost(path);
  13. post.setEntity(entity);
  14. //4.創建請求客戶端,並執行請求,獲得相應
  15. DefaultHttpClient client = new DefaultHttpClient();
  16. HttpResponse res = client.execute(post);
  17. if(res.getStatusLine().getStatusCode() == 200){
  18. return true;
  19. }
  20. return false;
  21. }
在項目中用到SLL或者Https,cookie的時候使用這個開源項目很方便,如果沒用到的話,直接操作http協議的操作效率相對要高些。
Copyright © Linux教程網 All Rights Reserved