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

相关文章

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

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

Android DataBinding 与 MVVM使用详解

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

Android ViewBinding使用流程

《AndroidViewBinding使用流程》AndroidViewBinding是Jetpack组件,替代findViewById,提供类型安全、空安全和编译时检查,代码简洁且性能优化,相比Da... 目录一、核心概念二、ViewBinding优点三、使用流程1. 启用 ViewBinding (模块级

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

Android学习总结之Java和kotlin区别超详细分析

《Android学习总结之Java和kotlin区别超详细分析》Java和Kotlin都是用于Android开发的编程语言,它们各自具有独特的特点和优势,:本文主要介绍Android学习总结之Ja... 目录一、空安全机制真题 1:Kotlin 如何解决 Java 的 NullPointerExceptio

Linux网络配置之网桥和虚拟网络的配置指南

《Linux网络配置之网桥和虚拟网络的配置指南》这篇文章主要为大家详细介绍了Linux中配置网桥和虚拟网络的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 一、网桥的配置在linux系统中配置一个新的网桥主要涉及以下几个步骤:1.为yum仓库做准备,安装组件epel-re

python如何下载网络文件到本地指定文件夹

《python如何下载网络文件到本地指定文件夹》这篇文章主要为大家详细介绍了python如何实现下载网络文件到本地指定文件夹,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下...  在python中下载文件到本地指定文件夹可以通过以下步骤实现,使用requests库处理HTTP请求,并结合o

Linux高并发场景下的网络参数调优实战指南

《Linux高并发场景下的网络参数调优实战指南》在高并发网络服务场景中,Linux内核的默认网络参数往往无法满足需求,导致性能瓶颈、连接超时甚至服务崩溃,本文基于真实案例分析,从参数解读、问题诊断到优... 目录一、问题背景:当并发连接遇上性能瓶颈1.1 案例环境1.2 初始参数分析二、深度诊断:连接状态与

Android NDK版本迭代与FFmpeg交叉编译完全指南

《AndroidNDK版本迭代与FFmpeg交叉编译完全指南》在Android开发中,使用NDK进行原生代码开发是一项常见需求,特别是当我们需要集成FFmpeg这样的多媒体处理库时,本文将深入分析A... 目录一、android NDK版本迭代分界线二、FFmpeg交叉编译关键注意事项三、完整编译脚本示例四

Android与iOS设备MAC地址生成原理及Java实现详解

《Android与iOS设备MAC地址生成原理及Java实现详解》在无线网络通信中,MAC(MediaAccessControl)地址是设备的唯一网络标识符,本文主要介绍了Android与iOS设备M... 目录引言1. MAC地址基础1.1 MAC地址的组成1.2 MAC地址的分类2. android与I