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

相关文章

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

Android 实现一个隐私弹窗功能

《Android实现一个隐私弹窗功能》:本文主要介绍Android实现一个隐私弹窗功能,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧... 效果图如下:1. 设置同意、退出、点击用户协议、点击隐私协议的函数参数2. 《用户协议》、《隐私政策》设置成可点击的,且颜色要区分出来res/l

Android实现一键录屏功能(附源码)

《Android实现一键录屏功能(附源码)》在Android5.0及以上版本,系统提供了MediaProjectionAPI,允许应用在用户授权下录制屏幕内容并输出到视频文件,所以本文将基于此实现一个... 目录一、项目介绍二、相关技术与原理三、系统权限与用户授权四、项目架构与流程五、环境配置与依赖六、完整

Android 12解决push framework.jar无法开机的方法小结

《Android12解决pushframework.jar无法开机的方法小结》:本文主要介绍在Android12中解决pushframework.jar无法开机的方法,包括编译指令、框架层和s... 目录1. android 编译指令1.1 framework层的编译指令1.2 替换framework.ja

Android开发环境配置避坑指南

《Android开发环境配置避坑指南》本文主要介绍了Android开发环境配置过程中遇到的问题及解决方案,包括VPN注意事项、工具版本统一、Gerrit邮箱配置、Git拉取和提交代码、MergevsR... 目录网络环境:VPN 注意事项工具版本统一:android Studio & JDKGerrit的邮

Android实现定时任务的几种方式汇总(附源码)

《Android实现定时任务的几种方式汇总(附源码)》在Android应用中,定时任务(ScheduledTask)的需求几乎无处不在:从定时刷新数据、定时备份、定时推送通知,到夜间静默下载、循环执行... 目录一、项目介绍1. 背景与意义二、相关基础知识与系统约束三、方案一:Handler.postDel

Qt实现网络数据解析的方法总结

《Qt实现网络数据解析的方法总结》在Qt中解析网络数据通常涉及接收原始字节流,并将其转换为有意义的应用层数据,这篇文章为大家介绍了详细步骤和示例,感兴趣的小伙伴可以了解下... 目录1. 网络数据接收2. 缓冲区管理(处理粘包/拆包)3. 常见数据格式解析3.1 jsON解析3.2 XML解析3.3 自定义