Android网络HttpURLConnection和HttpClient

2024-06-04 12:08

本文主要是介绍Android网络HttpURLConnection和HttpClient,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.概念      

      HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。在 JDK 的 java.net 包中已经提供了访问 HTTP 协议的基本功能:HttpURLConnection。但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。

      除此之外,在Android中,androidSDK中集成了ApacheHttpClient模块,用来提供高效的、最新的、功能丰富的支持 HTTP 协议工具包,并且它支持 HTTP 协议最新的版本和建议。使用HttpClient可以快速开发出功能强大的Http程序。

2.区别

HttpClient是个很不错的开源框架,封装了访问http的请求头,参数,内容体,响应等等,

HttpURLConnection是java的标准类,什么都没封装,用起来太原始,不方便,比如重访问的自定义,以及一些高级功能等。

 

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

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();  return null;  } catch (IOException e) {  e.printStackTrace();  return null;  }  }  //向服务器发送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;  }  }  

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"},  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("没有有效的数据!");  }  //和服务器连接  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();  }  


这篇关于Android网络HttpURLConnection和HttpClient的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1030042

相关文章

Debian 13升级后网络转发等功能异常怎么办? 并非错误而是管理机制变更

《Debian13升级后网络转发等功能异常怎么办?并非错误而是管理机制变更》很多朋友反馈,更新到Debian13后网络转发等功能异常,这并非BUG而是Debian13Trixie调整... 日前 Debian 13 Trixie 发布后已经有众多网友升级到新版本,只不过升级后发现某些功能存在异常,例如网络转

Android协程高级用法大全

《Android协程高级用法大全》这篇文章给大家介绍Android协程高级用法大全,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友跟随小编一起学习吧... 目录1️⃣ 协程作用域(CoroutineScope)与生命周期绑定Activity/Fragment 中手

Python开发简易网络服务器的示例详解(新手入门)

《Python开发简易网络服务器的示例详解(新手入门)》网络服务器是互联网基础设施的核心组件,它本质上是一个持续运行的程序,负责监听特定端口,本文将使用Python开发一个简单的网络服务器,感兴趣的小... 目录网络服务器基础概念python内置服务器模块1. HTTP服务器模块2. Socket服务器模块

Android 缓存日志Logcat导出与分析最佳实践

《Android缓存日志Logcat导出与分析最佳实践》本文全面介绍AndroidLogcat缓存日志的导出与分析方法,涵盖按进程、缓冲区类型及日志级别过滤,自动化工具使用,常见问题解决方案和最佳实... 目录android 缓存日志(Logcat)导出与分析全攻略为什么要导出缓存日志?按需过滤导出1. 按

Go语言网络故障诊断与调试技巧

《Go语言网络故障诊断与调试技巧》在分布式系统和微服务架构的浪潮中,网络编程成为系统性能和可靠性的核心支柱,从高并发的API服务到实时通信应用,网络的稳定性直接影响用户体验,本文面向熟悉Go基本语法和... 目录1. 引言2. Go 语言网络编程的优势与特色2.1 简洁高效的标准库2.2 强大的并发模型2.

Android Paging 分页加载库使用实践

《AndroidPaging分页加载库使用实践》AndroidPaging库是Jetpack组件的一部分,它提供了一套完整的解决方案来处理大型数据集的分页加载,本文将深入探讨Paging库... 目录前言一、Paging 库概述二、Paging 3 核心组件1. PagingSource2. Pager3.

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期

Android ClassLoader加载机制详解

《AndroidClassLoader加载机制详解》Android的ClassLoader负责加载.dex文件,基于双亲委派模型,支持热修复和插件化,需注意类冲突、内存泄漏和兼容性问题,本文给大家介... 目录一、ClassLoader概述1.1 类加载的基本概念1.2 android与Java Class

Linux中压缩、网络传输与系统监控工具的使用完整指南

《Linux中压缩、网络传输与系统监控工具的使用完整指南》在Linux系统管理中,压缩与传输工具是数据备份和远程协作的桥梁,而系统监控工具则是保障服务器稳定运行的眼睛,下面小编就来和大家详细介绍一下它... 目录引言一、压缩与解压:数据存储与传输的优化核心1. zip/unzip:通用压缩格式的便捷操作2.

Android DataBinding 与 MVVM使用详解

《AndroidDataBinding与MVVM使用详解》本文介绍AndroidDataBinding库,其通过绑定UI组件与数据源实现自动更新,支持双向绑定和逻辑运算,减少模板代码,结合MV... 目录一、DataBinding 核心概念二、配置与基础使用1. 启用 DataBinding 2. 基础布局