Java中HttpURLConnection与HttpClient

来源:互联网 发布:java 可变参数 null 编辑:程序博客网 时间:2024/06/05 13:32

HttpURLConnection的api:  http://docs.oracle.com/javase/8/docs/api/ 

HttpClient的文档:http://hc.apache.org/httpcomponents-client-ga/tutorial/html/index.html

HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。在 JDK 的 java.net 包中已经提供了访问 HTTP 协议的基本功能:HttpURLConnection。 

       HttpURLConnection是java的标准类,HttpURLConnection继承自URLConnection,可用于向指定网站发送GET请求、POST请求。

       在一般情况下,如果只是需要Web站点的某个简单页面提交请求并获取服务器响应,HttpURLConnection完全可以胜任。但在绝大部分情况下,Web站点的网页可能没这么简单,这些页面并不是通过一个简单的URL就可访问的,可能需要用户登录而且具有相应的权限才可访问该页面。在这种情况下,就需要涉及Session、Cookie的处理了,如果打算使用HttpURLConnection来处理这些细节,当然也是可能实现的,只是处理起来难度就大了。

       为了更好地处理向Web站点请求,包括处理Session、Cookie等细节问题,Apache开源组织提供了一个HttpClient项目,看它的名称就知道,它是一个简单的HTTP客户端(并不是浏览器),可以用于发送HTTP请求,接收HTTP响应。但不会缓存服务器的响应,不能执行HTML页面中嵌入的Javascript代码;也不会对页面内容进行任何解析、处理。

       简单来说,HttpClient就是一个增强版的HttpURLConnection,HttpURLConnection可以做的事情HttpClient全部可以做;HttpURLConnection没有提供的有些功能,HttpClient也提供了,但它只是关注于如何发送请求、接收
响应,以及管理HTTP连接。
       使用HttpClient发送请求、接收响应很简单,只要如下几步即可。
  1. 创建HttpClient对象。
  2. 如果需要发送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对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
       另外,Android已经成功地集成了HttpClient,这意味着开发人员可以直接在Android应用中使用Httpclient来访问提交请求、接收响应。
       比如一个Android应用需要向指定页面发送请求,但该页面并不是一个简单的页面,只有当用户已经登录,而且登录用户的用户名有效时才可访问该页面。如果使用HttpURLConnection来访问这个被保护的页面,那么需要处理的细节就太复杂了。
       其实访问Web应用中被保护的页面,使用浏览器则十分简单,用户通过系统提供的登录页面登录系统,浏览器会负责维护与服务器之间的Sesion,如果用户登录的用户名、密码符合要求,就可以访问被保护资源了。
       在Android应用程序中,则可使用HttpClient来登录系统,只要应用程序使用同一个HttpClient发送请求,HttpClient会自动维护与服务器之间的Session状态,也就是说程序第一次使用HttpClient登录系统后,接下来使用HttpClient即可访问被保护页而了。
在安卓开发上,虽然HttpClient更好地支持很多细节的控制(如代理、COOKIE、鉴权、压缩、连接池),但相应地对开发人员要求更高,代码写起来更复杂,普通开发人员很难做到对它很好地驾驭,官方的支持也越来越少;而HttpUrlConnection对大部分工作进行了包装,屏蔽了不需要的细节,更适合开发人员直接调用,而且官方对它的支持和优化也会越来越好。我们既然是做安卓应用的开发,自然要遵循安卓官方的指引,选用HttpUrlConnection。
谷歌推荐用HttpUrlConnection,对它进行了大量的优化。
以下是个人写的简单的例子:
HttpUrlConnection的get方法:
final URL url = new URL(Uri);HttpURLConnection connection = (HttpURLConnection) url.openConnection();InputStream is = new BufferedInputStream(connection.getInputStream());
HttpUrlConnection的post方法:
publicString doPost(String username,String password){try{url =newURL(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 =newDataOutputStream(uRLConnection.getOutputStream());String content = "username="+username+"&password="+password;out.writeBytes(content);out.flush();out.close();InputStream is = uRLConnection.getInputStream();BufferedReader br =newBufferedReader(newInputStreamReader(is));String response = "";String readLine =null;while((readLine =br.readLine()) !=null){//response = br.readLine();response = response + readLine;}is.close();br.close();uRLConnection.disconnect();returnresponse;}catch(MalformedURLException e) {e.printStackTrace();returnnull;}catch(IOException e) {e.printStackTrace();returnnull;}}

HttpClient的doget 方法:
public static String doGet(String urlAddress) {String getUrl = urlAddress;HttpGet httpGet = new HttpGet(getUrl);HttpParams hp = httpGet.getParams();hp.getParameter("true");// hp.// httpGet.setpHttpClient hc = HttpClients.createDefault();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 blocke.printStackTrace();return "exception";} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();return "exception";}}

HttpClient的dopost的方法:
public static String doPost(String urlAddress, String grant_type, String appid, String secret, String code) {// String getUrl = urlAddress +// "?username="+username+"&password="+password;HttpPost httpPost = new HttpPost(urlAddress);List params = new ArrayList();NameValuePair pair1 = new BasicNameValuePair("grant_type", grant_type);NameValuePair pair2 = new BasicNameValuePair("appid", appid);NameValuePair pair3 = new BasicNameValuePair("secret", secret);NameValuePair pair4 = new BasicNameValuePair("code", code);params.add(pair1);params.add(pair2);params.add(pair3);params.add(pair4);HttpEntity he;try {he = new UrlEncodedFormEntity(params, "gbk");httpPost.setEntity(he);} catch (UnsupportedEncodingException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}HttpClient hc = HttpClients.createDefault();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 {System.out.println("连接不成功");return "error";}} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();return "exception";} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();return "exception";}}



0 0
原创粉丝点击