• <kbd id="qyk40"></kbd>
  • <strike id="qyk40"></strike><samp id="qyk40"><pre id="qyk40"></pre></samp>

    Android網(wǎng)絡(luò)連接之HttpURLConnection和HttpClient

    1.概念      

          HTTP 協(xié)議可能是現(xiàn)在 Internet 上使用得最多、最重要的協(xié)議了,越來越多的 Java 應(yīng)用程序需要直接通過 HTTP  協(xié)議來訪問網(wǎng)絡(luò)資源。在 JDK 的 java.net 包中已經(jīng)提供了訪問 HTTP  協(xié)議的基本功能:HttpURLConnection。但是對于大部分應(yīng)用程序來說,JDK 庫本身提供的功能還不夠豐富和靈活。

          除此之外,在Android中,androidSDK中集成了Apache的HttpClient模塊,用來提供高效的、最新的、功能豐富的支持 HTTP 協(xié)議工具包,并且它支持 HTTP 協(xié)議最新的版本和建議。使用HttpClient可以快速開發(fā)出功能強(qiáng)大的Http程序。

    2.區(qū)別

    HttpClient是個(gè)很不錯(cuò)的開源框架,封裝了訪問http的請求頭,參數(shù),內(nèi)容體,響應(yīng)等等,

    HttpURLConnection是java的標(biāo)準(zhǔn)類,什么都沒封裝,用起來太原始,不方便,比如重訪問的自定義,以及一些高級功能等。

     

    URLConnection

    HTTPClient

    Proxies and SOCKS

    Full support in Netscape browser, appletviewer, and applications  (SOCKS: Version 4 only); no additional limitations from security  policies.

    Full support (SOCKS: Version 4 and 5); limited in applets however by  security policies; in Netscape can't pick up the settings from the  browser.

    Authorization

    Full support for Basic Authorization in Netscape (can use info given  by the user for normal accesses outside of the applet); no support in  appletviewer or applications.

    Full support everywhere; however cannot access previously given info  from Netscape, thereby possibly requesting the user to enter info (s)he  has already given for a previous access. Also, you can add/implement  additional authentication mechanisms yourself.

    Methods

    Only has GET and POST.

    Has HEAD, GET, POST, PUT, DELETE, TRACE and OPTIONS, plus any arbitrary method.

    Headers

    Currently you can only set any request headers if you are doing a  POST under Netscape; for GETs and the JDK you can't set any headers. 
    Under  Netscape 3.0 you can read headers only if the resource was returned  with a Content-length header; if no Content-length header was returned,  or under previous versions of Netscape, or using the JDK no headers can  be read.

    Allows any arbitrary headers to be sent and received.

    Automatic Redirection Handling

    Yes.

    Yes (as allowed by the HTTP/1.1 spec).

    Persistent Connections

    No support currently in JDK; under Netscape uses HTTP/1.0 Keep-Alive's.

    Supports HTTP/1.0 Keep-Alive's and HTTP/1.1 persistence.

    Pipelining of Requests

    No.

    Yes.

    Can handle protocols other than HTTP

    Theoretically; however only http is currently implemented.

    No.

    Can do HTTP over SSL (https)

    Under Netscape, yes. Using Appletviewer or in an application, no.

    No (not yet).

    Source code available

    No.

    Yes.

    3.案例

    URLConnection

    復(fù)制代碼

        String urlAddress = "http://192.168.1.102:8080/AndroidServer/login.do";  
        URL url;  
        HttpURLConnection uRLConnection;  
        public UrlConnectionToServer(){  
      
        }  

     

        //向服務(wù)器發(fā)送get請求
        public String doGet(String username,String password){  
            String getUrl = urlAddress + "?username="+username+"&password="+password;  
            try {  
                url = new URL(getUrl);  
                uRLConnection = (HttpURLConnection)url.openConnection();  
                InputStream is = uRLConnection.getInputStream();  
                BufferedReader br = new BufferedReader(new InputStreamReader(is));  
                String response = "";  
                String readLine = null;  
                while((readLine =br.readLine()) != null){  
                    //response = br.readLine();  
                    response = response + readLine;  
                }  
                is.close();  
                br.close();  
                uRLConnection.disconnect();  
                return response;  
            } catch (MalformedURLException e) {  
                e.printStackTrace();  
                return null;  
            } catch (IOException e) {  
                e.printStackTrace();  
                return null;  
            }  
        }  
          

     

        //向服務(wù)器發(fā)送post請求
        public String doPost(String username,String password){  
            try {  
                url = new URL(urlAddress);  
                uRLConnection = (HttpURLConnection)url.openConnection();  
                uRLConnection.setDoInput(true);  
                uRLConnection.setDoOutput(true);  
                uRLConnection.setRequestMethod("POST");  
                uRLConnection.setUseCaches(false);  
                uRLConnection.setInstanceFollowRedirects(false);  
                uRLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");  
                uRLConnection.connect();  
                  
                DataOutputStream out = new DataOutputStream(uRLConnection.getOutputStream());  
                String content = "username="+username+"&password="+password;  
                out.writeBytes(content);  
                out.flush();  
                out.close();  
                  
                InputStream is = uRLConnection.getInputStream();  
                BufferedReader br = new BufferedReader(new InputStreamReader(is));  
                String response = "";  
                String readLine = null;  
                while((readLine =br.readLine()) != null){  
                    //response = br.readLine();  
                    response = response + readLine;  
                }  
                is.close();  
                br.close();  
                uRLConnection.disconnect();  
                return response;  
            } catch (MalformedURLException e) {  
                e.printStackTrace();  
                return null;  
            } catch (IOException e) {  
                e.printStackTrace();  
                return null;  
            }  
        }  

    復(fù)制代碼

    HTTPClient

    復(fù)制代碼

    String urlAddress = "http://192.168.1.102:8080/qualityserver/login.do";  
    public HttpClientServer(){  
              
     }  
          
    public String doGet(String username,String password){  
        String getUrl = urlAddress + "?username="+username+"&password="+password;  
        HttpGet httpGet = new HttpGet(getUrl);  
        HttpParams hp = httpGet.getParams();  
        hp.getParameter("true");  
        //hp.  
        //httpGet.setp  
        HttpClient hc = new DefaultHttpClient();  
        try {  
            HttpResponse ht = hc.execute(httpGet);  
            if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){  
                HttpEntity he = ht.getEntity();  
                InputStream is = he.getContent();  
                BufferedReader br = new BufferedReader(new InputStreamReader(is));  
                String response = "";  
                String readLine = null;  
                while((readLine =br.readLine()) != null){  
                    //response = br.readLine();  
                    response = response + readLine;  
                }  
                is.close();  
                br.close();  
                  
                //String str = EntityUtils.toString(he);  
                System.out.println("========="+response);  
                return response;  
            }else{  
                return "error";  
            }  
        } catch (ClientProtocolException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
            return "exception";  
        } catch (IOException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
            return "exception";  
        }      
    }  
      
    public String doPost(String username,String password){  
        //String getUrl = urlAddress + "?username="+username+"&password="+password;  
        HttpPost httpPost = new HttpPost(urlAddress);  
        List params = new ArrayList();  
        NameValuePair pair1 = new BasicNameValuePair("username", username);  
        NameValuePair pair2 = new BasicNameValuePair("password", password);  
        params.add(pair1);  
        params.add(pair2);  
          
        HttpEntity he;  
        try {  
            he = new UrlEncodedFormEntity(params, "gbk");  
            httpPost.setEntity(he);  
              
        } catch (UnsupportedEncodingException e1) {  
            // TODO Auto-generated catch block  
            e1.printStackTrace();  
        }   
          
        HttpClient hc = new DefaultHttpClient();  
        try {  
            HttpResponse ht = hc.execute(httpPost);  
            //連接成功  
            if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){  
                HttpEntity het = ht.getEntity();  
                InputStream is = het.getContent();  
                BufferedReader br = new BufferedReader(new InputStreamReader(is));  
                String response = "";  
                String readLine = null;  
                while((readLine =br.readLine()) != null){  
                    //response = br.readLine();  
                    response = response + readLine;  
                }  
                is.close();  
                br.close();  
                  
                //String str = EntityUtils.toString(he);  
                System.out.println("=========&&"+response);  
                return response;  
            }else{  
                return "error";  
            }  
        } catch (ClientProtocolException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
            return "exception";  
        } catch (IOException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
            return "exception";  
        }     
    }  

    復(fù)制代碼

    servlet端json轉(zhuǎn)化: 

    復(fù)制代碼

            resp.setContentType("text/json");  
            resp.setCharacterEncoding("UTF-8");  
            toDo = new ToDo();  
            List<UserBean> list = new ArrayList<UserBean>();  
            list = toDo.queryUsers(mySession);  
            String body;  
    
            //設(shè)定JSON  
            JSONArray array = new JSONArray();  
            for(UserBean bean : list)  
            {  
                JSONObject obj = new JSONObject();  
                try  
                {  
                     obj.put("username", bean.getUserName());  
                     obj.put("password", bean.getPassWord());  
                 }catch(Exception e){}  
                 array.add(obj);  
            }  
            pw.write(array.toString());  
            System.out.println(array.toString());  

    復(fù)制代碼

    android端接收:

    復(fù)制代碼

    String urlAddress = "http://192.168.1.102:8080/qualityserver/result.do";  
            String body =   
                getContent(urlAddress);  
            JSONArray array = new JSONArray(body);            
            for(int i=0;i<array.length();i++)  
            {  
                obj = array.getJSONObject(i);  
                sb.append("用戶名:").append(obj.getString("username")).append("\t");  
                sb.append("密碼:").append(obj.getString("password")).append("\n");  
                  
                HashMap<String, Object> map = new HashMap<String, Object>();  
                try {  
                    userName = obj.getString("username");  
                    passWord = obj.getString("password");  
                } catch (JSONException e) {  
                    e.printStackTrace();  
                }  
                map.put("username", userName);  
                map.put("password", passWord);  
                listItem.add(map);  
                  
            }  
              
            } catch (Exception e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
              
            if(sb!=null)  
            {  
                showResult.setText("用戶名和密碼信息:");  
                showResult.setTextSize(20);  
            } else  
                extracted();  
       
           //設(shè)置adapter   
            SimpleAdapter simple = new SimpleAdapter(this,listItem,  
                    android.R.layout.simple_list_item_2,  
                    new String[]{"username","password"},  
                    new int[]{android.R.id.text1,android.R.id.text2});  
            listResult.setAdapter(simple);  
              
            listResult.setOnItemClickListener(new OnItemClickListener() {  
                @Override  
                public void onItemClick(AdapterView<?> parent, View view,  
                        int position, long id) {  
                    int positionId = (int) (id+1);  
                    Toast.makeText(MainActivity.this, "ID:"+positionId, Toast.LENGTH_LONG).show();  
                  
                }  
            });  
        }  
        private void extracted() {  
            showResult.setText("沒有有效的數(shù)據(jù)!");  
        }  
        //和服務(wù)器連接  
        private String getContent(String url)throws Exception{  
            StringBuilder sb = new StringBuilder();  
            HttpClient client =new DefaultHttpClient();  
            HttpParams httpParams =client.getParams();  
              
            HttpConnectionParams.setConnectionTimeout(httpParams, 3000);  
            HttpConnectionParams.setSoTimeout(httpParams, 5000);  
            HttpResponse response = client.execute(new HttpGet(url));  
            HttpEntity entity =response.getEntity();  
              
            if(entity !=null){  
                BufferedReader reader = new BufferedReader(new InputStreamReader  
                        (entity.getContent(),"UTF-8"),8192);  
                String line =null;  
                while ((line= reader.readLine())!=null){  
                    sb.append(line +"\n");  
                }  
                reader.close();  
            }  
            return sb.toString();  
        }  

     

    穩(wěn)定

    產(chǎn)品高可用性高并發(fā)

    貼心

    項(xiàng)目群及時(shí)溝通

    專業(yè)

    產(chǎn)品經(jīng)理1v1支持

    快速

    MVP模式小步快跑

    承諾

    我們選擇聲譽(yù)

    堅(jiān)持

    10年專注高端品質(zhì)開發(fā)
    • 返回頂部
    精品国产免费一区二区三区| 中文字幕日韩三级| 日韩精品免费一区二区三区| 老汉精品免费AV在线播放| 日韩爆乳一区二区无码| 91精品国产麻豆国产自产在线 | 日韩毛片免费无码无毒视频观看| 杨幂精品国产福利在线| 热99re久久国超精品首页| 国产精品亚洲w码日韩中文| 99久久精品全部| 亚洲精品动漫人成3d在线| 久久国产精品99国产精| 日本一区二区三区精品中文字幕| 亚洲精品无码99在线观看 | 自拍日韩亚洲一区在线| 久久精品国产亚洲av麻豆蜜芽| CAOPORM国产精品视频免费| 亚洲欧洲日韩极速播放| 中日韩产精品1卡二卡三卡| 国产成人精品亚洲一区| 91大神精品在线观看| 精品久久久无码中文字幕| 亚洲精品国产电影| d动漫精品专区久久| 精品久久久久国产免费| 亚洲综合精品香蕉久久网97| 国产精品国产高清国产专区| 精品久久国产视频| 亚洲精品欧洲精品| 国产在线精品无码二区| 亚洲AV日韩AV无码污污网站| 日韩社区一区二区三区| 国产伦子系列麻豆精品| 99久久久精品免费观看国产| 久久久精品国产亚洲成人满18免费网站| 国产成人综合色视频精品| 在线观看精品国产福利片100| 在线观看精品国产福利片100| 日韩国产成人资源精品视频| 9999国产精品欧美久久久久久|