多多色-多人伦交性欧美在线观看-多人伦精品一区二区三区视频-多色视频-免费黄色视屏网站-免费黄色在线

國內最全IT社區平臺 聯系我們 | 收藏本站
阿里云優惠2
您當前位置:首頁 > php開源 > 綜合技術 > URLConnection和HTTPClient的比較

URLConnection和HTTPClient的比較

來源:程序員人生   發布時間:2015-04-30 08:58:03 閱讀次數:4101次

1.概念      

      HTTP 協議多是現在 Internet 上使用得最多、最重要的協議了,愈來愈多的 Java 利用程序需要直接通過 HTTP 協議來訪問網絡資源。在 JDK 的 java.net 包中已提供了訪問 HTTP 協議的基本功能:HttpURLConnection。但是對大部份利用程序來講,JDK 庫本身提供的功能還不夠豐富和靈活。

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

2.區分

HttpClient是個很不錯的開源框架,封裝了訪問http的要求頭,參數,內容體,響應等等,

HttpURLConnection是java的標準類,甚么都沒封裝,用起來太原始,不方便,比如重訪問的自定義,和1些高級功能等。

3.案例

URLConnection

String urlAddress = "http://192.168.1.102:8080/AndroidServer/login.do"; URL url; HttpURLConnection uRLConnection; public UrlConnectionToServer(){ } //向服務器發送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(); returnnull; } catch (IOException e) { e.printStackTrace(); returnnull; } } //向服務器發送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(); returnnull; } catch (IOException e) { e.printStackTrace(); returnnull; } }
HTTPClient

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"; } }
servlet端json轉化: 
resp.setContentType("text/json"); resp.setCharacterEncoding("UTF⑻"); toDo = new ToDo(); List<UserBean> list = new ArrayList<UserBean>(); list = toDo.queryUsers(mySession); String body; //設定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());
android端接收
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(" "); sb.append("密碼:").append(obj.getString("password")).append(" "); 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(); //設置adapter SimpleAdapter simple = new SimpleAdapter(this,listItem, android.R.layout.simple_list_item_2, new String[]{"username","password"}, newint[]{android.R.id.text1,android.R.id.text2}); listResult.setAdapter(simple); listResult.setOnItemClickListener(new OnItemClickListener() { @Override publicvoid onItemClick(AdapterView<?> parent, View view, int position, long id) { int positionId = (int) (id+1); Toast.makeText(MainActivity.this, "ID:"+positionId, Toast.LENGTH_LONG).show(); } }); } privatevoid extracted() { showResult.setText("沒有有效的數據!"); } //和服務器連接 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⑻"),8192); String line =null; while ((line= reader.readLine())!=null){ sb.append(line +" "); } reader.close(); } return sb.toString(); }

 

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.

生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈
程序員人生
------分隔線----------------------------
分享到:
------分隔線----------------------------
關閉
程序員人生
主站蜘蛛池模板: 亚洲丶国产丶欧美一区二区三区 | 久久人人澡人人爽人人爱 | 手机看片福利在线 | 国产一精品一aⅴ一免费 | 国产精品乱码免费一区二区 | 亚洲成人图 | 国产尤物视频在线 | 成人久久久精品乱码一区二区三区 | 久久精品久久精品国产大片 | 国产aaa免费视频国产 | 午夜免费啪视频观看网站 | 精彩视频在线观看 | 欧洲三级网站 | 国产精品久久久久久久久久一区 | 老司机成人在线视频 | 亚洲人成依人成综合网 | 叼嘿视频在线免费观看 | 日韩天堂 | 久久入| 成人三级精品视频在线观看 | 欧美日一级 | 免费视频性 | 亚洲www网站 | 欧美性受xxxx黑人xyx性爽 | 国产成人久视频免费 | 日本高清不卡免费 | 依人久久 | 欧美黑人巨大xxxxx视频 | 最近中字视频在线观看 | 欧美一级毛片免费大片 | 欧美在线色| 乱老女人一二区视频 | 亚洲精品综合一区二区三区在线 | 亚洲图片二区 | 天堂免费观看 | 校园春色 亚洲色图 | 在线中文字幕亚洲 | 久久亚洲不卡一区二区 | 国产精品视频流白浆免费视频 | 小说区图片区亚洲 | 美女上床视频 |