转自http://blog.sina.com.cn/s/blog_6610da3901012doz.html
A Comparison of java.net.URLConnection and HTTPClient
Since java.net.URLConnection and HTTPClient have overlappingfunctionalities, the question arises of why would you use HTTPClient.Here are a few of the capabilites and tradeoffs.
1.概念
HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。在 JDK 的 java.net 包中已经提供了访问 HTTP 协议的基本功能:HttpURLConnection。但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。
除此之外,在Android中,androidSDK中集成了Apache的HttpClient模块,用来提供高效的、最新的、功能丰富的支持 HTTP 协议工具包,并且它支持 HTTP 协议最新的版本和建议。使用HttpClient可以快速开发出功能强大的Http程序。
2.区别
HttpClient是个很不错的开源框架,封装了访问http的请求头,参数,内容体,响应等等,
HttpURLConnection是java的标准类,什么都没封装,用起来太原始,不方便,比如重访问的自定义,以及一些高级功能等。
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-8"); 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("\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(); //设置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-8"),8192); String line =null; while ((line= reader.readLine())!=null){ sb.append(line +"\n"); } reader.close(); } return sb.toString(); }
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. |
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. |
Only has GET and POST. |
Has HEAD, GET, POST, PUT, DELETE, TRACE and OPTIONS, plus any arbitrary method. |
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. |
Allows any arbitrary headers to be sent and received. |
Yes. |
Yes (as allowed by the HTTP/1.1 spec). |
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. |
No. |
Yes. |
Theoretically; however only http is currently implemented. |
No. |
Under Netscape, yes. Using Appletviewer or in an application, no. |
No (not yet). |
No. |
Yes. |
相关推荐
URLConnection和HttpClient使用入门
NULL 博文链接:https://xiaowei-qi-epro-com-cn.iteye.com/blog/1973295
在android项目中,经常需要用到网络,而在联网之前前,我们都要做一次网络的判断,判断当前的网络状态是否可用,然后开始请求网络。 android中请求网络方式有:HttpURLConnection和HttpClient
本篇文章主要介绍了Java两种方式简单实现:爬取网页并且保存 ,主要用UrlConnection、HttpClient爬取实现,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。
NULL 博文链接:https://bijian1013.iteye.com/blog/2299764
1.基于HttpClient-4.4.1封装的一个工具类; 2.基于HttpAsycClient-4.1封装的异步HttpClient工具类; 3.javanet包下面是基于jdk自带的UrlConnection进行封装的。 前2个工具类支持插件式配置Header、插件式配置...
在android 2.0平台上分别使用URLConnection和HttpClient两种方式实现对WebService的Get及Post调用的eclipse工程源代码。
内容概要:Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且也方便了开发人员测试接口...
HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。 下载地址: http://hc.apache.org/downloads.cgi 1.2特性 1. 基于标准、纯净的java语言。...
HttpClient4.5版本所需的全部jar包,HttpClient相比传统JDK自带的URLConnection增加了易用性和灵活性
HttpClient是Apache Jakarta Common下的子项目,用来提供高效的...它已经被Apache HttpClient和HttpCore模块中的HttpComponents项目所取代,这些模块提供了更好的性能和更多的灵活性 ————————————————
HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性,它不仅使客户端发送HTTP请求变得容易,而且也方便了开发人员测试接口(基于Http协议的),即提高了开发的效率,也方便提高代码的健壮性。
android与服务器间的通信开发,利用URL,URLConnection,HTTPClient开发
主要用于截取页面!虽然有HttpClient但是有时候这个还是比较有用的!
本例子是一个使用HttpClient和URLConnection获取网页html内容的小例子,获取到的源码不解析直接显示,技术比较简单,需要的朋友可以下载研究一下,项目编码GBK默认编译版本2.3.3
所用知识:http网络请求(url urlConnection HttpURLConnection HttpClient)、 volley、 MediaPlay、 video、webView、Json解析 等 功能:个人 http 简单的网路请求测试工具。 测试 url 网络资源请求获取 url.open...
第一讲:Android开发环境的搭建 第二讲:Android系统构架分析和应用程序目录结构分析 第三讲:Android模拟器的使用 emulator 第四讲:Activity入门指南 Activity ...第三十讲:URLConnection和HttpClient使用入门
本例子是一个使用HttpClient和URLConnection获取网页html内容的小例子,获取到的源码不解析直接显示,技术比较简单,需要的朋友可以下载研究一下,项目编码GBK默认编译版本2.3.3
Android中提供的HttpURLConnection和HttpClient接口可以用来开发HTTP程序。以下是学习中的一些经验。 1、HttpURLConnection接口 首先需要明确的是,Http通信中的POST和GET请求方式的不同。GET可以获得静态页面,...
在网上寻找之后,发现是使用HttClient来进行响应的操作,起初尝试多次依然不能传递参数和传递文件,后来发现时因为当使用HttpClient时,不能使用request.getParameter()对普通参数进行获取,而要在服务器端使用...