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

相关文章

C#使用HttpClient进行Post请求出现超时问题的解决及优化

《C#使用HttpClient进行Post请求出现超时问题的解决及优化》最近我的控制台程序发现有时候总是出现请求超时等问题,通常好几分钟最多只有3-4个请求,在使用apipost发现并发10个5分钟也... 目录优化结论单例HttpClient连接池耗尽和并发并发异步最终优化后优化结论我直接上优化结论吧,

SSID究竟是什么? WiFi网络名称及工作方式解析

《SSID究竟是什么?WiFi网络名称及工作方式解析》SID可以看作是无线网络的名称,类似于有线网络中的网络名称或者路由器的名称,在无线网络中,设备通过SSID来识别和连接到特定的无线网络... 当提到 Wi-Fi 网络时,就避不开「SSID」这个术语。简单来说,SSID 就是 Wi-Fi 网络的名称。比如

Java实现任务管理器性能网络监控数据的方法详解

《Java实现任务管理器性能网络监控数据的方法详解》在现代操作系统中,任务管理器是一个非常重要的工具,用于监控和管理计算机的运行状态,包括CPU使用率、内存占用等,对于开发者和系统管理员来说,了解这些... 目录引言一、背景知识二、准备工作1. Maven依赖2. Gradle依赖三、代码实现四、代码详解五

Android数据库Room的实际使用过程总结

《Android数据库Room的实际使用过程总结》这篇文章主要给大家介绍了关于Android数据库Room的实际使用过程,详细介绍了如何创建实体类、数据访问对象(DAO)和数据库抽象类,需要的朋友可以... 目录前言一、Room的基本使用1.项目配置2.创建实体类(Entity)3.创建数据访问对象(DAO

Android WebView的加载超时处理方案

《AndroidWebView的加载超时处理方案》在Android开发中,WebView是一个常用的组件,用于在应用中嵌入网页,然而,当网络状况不佳或页面加载过慢时,用户可能会遇到加载超时的问题,本... 目录引言一、WebView加载超时的原因二、加载超时处理方案1. 使用Handler和Timer进行超

Linux 网络编程 --- 应用层

一、自定义协议和序列化反序列化 代码: 序列化反序列化实现网络版本计算器 二、HTTP协议 1、谈两个简单的预备知识 https://www.baidu.com/ --- 域名 --- 域名解析 --- IP地址 http的端口号为80端口,https的端口号为443 url为统一资源定位符。CSDNhttps://mp.csdn.net/mp_blog/creation/editor

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

Android平台播放RTSP流的几种方案探究(VLC VS ExoPlayer VS SmartPlayer)

技术背景 好多开发者需要遴选Android平台RTSP直播播放器的时候,不知道如何选的好,本文针对常用的方案,做个大概的说明: 1. 使用VLC for Android VLC Media Player(VLC多媒体播放器),最初命名为VideoLAN客户端,是VideoLAN品牌产品,是VideoLAN计划的多媒体播放器。它支持众多音频与视频解码器及文件格式,并支持DVD影音光盘,VCD影

ASIO网络调试助手之一:简介

多年前,写过几篇《Boost.Asio C++网络编程》的学习文章,一直没机会实践。最近项目中用到了Asio,于是抽空写了个网络调试助手。 开发环境: Win10 Qt5.12.6 + Asio(standalone) + spdlog 支持协议: UDP + TCP Client + TCP Server 独立的Asio(http://www.think-async.com)只包含了头文件,不依

poj 3181 网络流,建图。

题意: 农夫约翰为他的牛准备了F种食物和D种饮料。 每头牛都有各自喜欢的食物和饮料,而每种食物和饮料都只能分配给一头牛。 问最多能有多少头牛可以同时得到喜欢的食物和饮料。 解析: 由于要同时得到喜欢的食物和饮料,所以网络流建图的时候要把牛拆点了。 如下建图: s -> 食物 -> 牛1 -> 牛2 -> 饮料 -> t 所以分配一下点: s  =  0, 牛1= 1~