URLConnection和HTTPClient的比较

Vivado 2024.1 与 Quartus Prime 23.1 对比评测:5大维度解析FPGA开发工具选型 本文对Vivado 2024.1和Quartus Prime 23.1两大FPGA开发工具进行了深度对比评测,从开发环境、编译性能、调试工具、IP生态系统和场景化选型5个维度展开分析。针对不同应用场景,为工程师提供专业的工具选型建议,帮助优化FPGA开发效率和项目性能。 阅读详情

A Comparison of java.net.URLConnection and HTTPClient

Since java.net.URLConnection and HTTPClient have overlappingfunctionalities, the question arises of why would you use HTTPClient.Here are a few of the capabilites and tradeoffs.

1.概念      

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

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

2.区别

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

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

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

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"},  newint[]{android.R.id.text1,android.R.id.text2});  listResult.setAdapter(simple);  listResult.setOnItemClickListener(new OnItemClickListener() {  @Override  publicvoid onItemClick(AdapterView<?> parent, View view,  int position, long id) {  int positionId = (int) (id+1);  Toast.makeText(MainActivity.this, "ID:"+positionId, Toast.LENGTH_LONG).show();  }  });  }  privatevoid 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();  }
 

URLConnection

HTTPClient

Proxies and SOCKS

Authorization

Methods

Headers

Automatic Redirection Handling

Persistent Connections

Pipelining of Requests

Can handle protocols other than HTTP

Can do HTTP over SSL (https)

Source code available

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.

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.

Only has GET and POST.

Has HEAD, GET, POST, PUT, DELETE, TRACE and OPTIONS, plus any arbitrary method.

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.

Yes.

Yes (as allowed by the HTTP/1.1 spec).

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.

No.

Yes.

Theoretically; however only http is currently implemented.

No.

Under Netscape, yes. Using Appletviewer or in an application, no.

No (not yet).

No.

Yes.

Java中URLConnection与Apache HttpClient发送HTTP请求的比较分析 在第五章中,我们分别分析了轻量级内置HTTP客户端和第三方HTTP客户端在不同业务场景下的适用性。通过对比URLConnection和HttpClient在API设计、异步请求处理、多线程支持等方面的表现,我们为技术选型提供了参考。同时,我们也通过代码示例进一步阐述了如何在实际开发中应用这些技术。这些内容对于IT行业从业者,尤其是需要处理HTTP请求的开发者,具有较高的参考价值。 阅读详情

相关推荐

车辆TBOX科普 第69次 TBOX行业发展趋势与就业前景深度解析

TBOX技术革新驱动汽车智能化发展 Telematics BOX(TBOX)正快速从车辆状态监控器进化为整车智能核心,市场年增速超25%,2025年规模将达150亿美元。技术呈现四大革新方向:5G与V2X集成实现多模通信网关,支持10-20Gbps高速传输;多模GNSS融合定位精度达厘米级,北斗系统提供独特优势;边缘计算架构使TBOX具备本地AI处理能力,减少95%数据上传;硬件安全模块(HSM)成为标配,满足EVITA标准的安全需求。这些技术突破正重塑TBOX架构,使其从单纯通信管道升级为智能网联汽车的关

IT深耕十余载,大道之简 1847

Http请求-HttpURLConnection、HttpClient

常见的Http请求方式

weixin_40017062的博客 1534

NY8A053E 例程 之 PWM Ouput

更多关于NY8A053E的相关例程请留言!

倪彬笑阳的博客 2948

HttpURLConnection与HttpClient

HttpURLConnection与HttpClient一.HttpURLConnection1.基本介绍2.提供的几个方法3.使用例子3.1使用GET方式访问HTTP3.2使用POST方式访问HTTP4.使用总结二.HttpClient1.基本介绍2.使用流程3.使用例子3.1使用GET方式访问HTTP3.2使用POST方式访问HTTP3.3POST和GET的区别4.使用总结三.表单提交中的po...

weixin_44275194的博客 2546

GraphSense介绍

GraphSense是一个跨账本加密货币分析平台 它的介绍在这里 代码也是开源的 graphsense-dashboard 用于交互式加密货币分析的Web仪表板。 可以看导进数据的情况 graphsense-transformation 基于spark/cassandra/java服务运行 GraphSense转换管道,用于将加密货币的区块/交易/标签等数据导入,可以看它指定的json格式: t...

幸福诗歌的博客 1086

Ubuntu下NVIDIA驱动安装全攻略:从报错到完美运行nvidia-smi的完整流程

本文提供了在Ubuntu系统中安装NVIDIA驱动的完整解决方案,重点解决因驱动版本冲突、内核模块未加载或Secure Boot安全启动导致的`nvidia-smi`报错问题。通过彻底清理旧驱动、处理Secure Boot、选择兼容版本并正确安装,最终确保驱动完美运行。

weixin_29196891的博客 367

HttpURLConnection与HttpClient浅析

HttpURLConnection与HttpClient浅析1. GET请求与POST请求HTTP协议是现在Internet上使用得最多、最重要的协议了,越来越多的Java应用程序需要直接通过HTTP协议来访问网络资源。在介绍HttpURLConnection前,我们还是再来说一下URL请求最常用的两种方式:GET请求与POST请求。GET请求的数据会附在URL之后(就是把数据放置在HTTP协议头中

小明的专栏 1万+

100天精通Python(爬虫篇)——第122天:基于selenium接管已启动的浏览器(反反爬策略)

100天精通Python(爬虫篇)——第122天:基于selenium接管已启动的浏览器(反反爬策略)

努力让自己发光,对的人才能迎着光而来 13万+

[转]URLConnection和HTTPClient的比较

转自http://blog.sina.com.cn/s/blog_6610da3901012doz.html A Comparison of java.net.URLConnection and HTTPClient Since java.net.URLConnection and HTTPClient have overlappingfunctionalities, the questio...

haliluya4的专栏 251

XSS漏洞之PDF生成:从XSS到服务端任意文件读取

XSS是最为常见的Web漏洞之一,多年来连续入选OWASP TOP10,相信大家都耳熟能详。 它是一种代码注入类的攻击,是一种客户端侧的攻击,攻击者通过在Web应用中注入恶意JavaScript代码,通过点击URL,最终在受害者浏览器端执行的一种漏洞。主要有反射型XSS、存储型XSS、基于DOM的XSS三类。XSS一些比较常规的危害大概有:重定向浏览器、窃取Cookie、浏览器劫持等。本文章侧重于发现XSS后的进一步利用。 主要介绍在某次实际测试过程中,发现XSS漏洞之后,如何进一步的利用,最终通过XSS达

计算机毕业论文源码,学生个人网页制作html源码。贴近用户做网络推广和互联网优化。 3787

【测开求职】面试题:数据结构 吐血整理

本篇文章是笔者为准备研究生复试以及校招而写,因此主要针对问答,注重理解,而不在于细节计算。涵盖考研范围内的所有知识内容,读者可以先查看上面的链接走一遍数据结构的整体框架结构。其中,重点难点以及易混淆的知识点,笔者用其他近30篇文章进行了详述,在知识点处贴好了链接,有需要的可以查阅。

vector的博客 7072

URLConnection跟HTTPClient的比较

A Comparison of java.net.URLConnection and HTTPClient Since java.net.URLConnection and HTTPClient have overlappingfunctionalities, the question arises of why would you use HTTPClient.Here are a few

hmchxy444的专栏 606

使用Simulink来模拟多旋翼无人机在风扰动条件下的飞行情况,并分析其稳定性

本教程详细介绍了使用Simulink进行多旋翼无人机风扰动稳定性分析的完整流程。首先构建包含飞行器动力学模型、控制系统和环境模拟模块的系统框架,重点讲解简化动力学方程的实现方法。随后指导设计PID控制器来维持姿态稳定,并添加随机风扰动模型模拟环境干扰。通过设置输入信号和输出显示,最终实现对不同风速条件下无人机控制性能的评估。该实例为无人机控制系统设计提供了实用的仿真方法,强调利用MATLAB工具进行可视化分析和参数优化,以提高系统抗干扰能力和稳定性。

amy_mhd的博客 427

httpclient和urlconnection比较

HttpClient是个很不错的开源框架,封装了访问http的请求头,参数,内容体,响应等等, HttpURLConnection是java的标准类,什么都没封装,用起来太原始,不方便,比如重访问的自定义,以及一些高级功能等。 HttpURLConnection是java的标准类,什么都没封装,用起来太原始,不方便,比如重访问的自定义,以及一些高级功能等。 H

cshhs的专栏 383

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

URLConnection and HTTPClient的比较

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

qq_29663071的博客 366

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

URLConnection and HTTPClient 比较

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

akingde 143

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

关于httpclient与socket与URLConnection(url)的比较笔记

socket是java底层的通信方式.使用的协议是tcp/ip。 URLConnection是java的某个类。 httpclient是java关于web的框架,算是对httpurlconnection(url)的封装。 三者关系,socket–>URLConnection–>httpclient。后者包含前者,前者更加底层。 URLConnection是表示Java应用程序和URL之...

zero_cctv的博客 584

java.net.URLConnection发送HTTP请求与通过Apache HttpClient发送HTTP请求比较

        由于前段时间对java.net.URLConnection和org.apache.http.impl.client.HttpClients发送HTTP请求有所接触,发现在使用过程中碰到一些不一样的地方,特简单记录下来,以免忘记。         如果要说它们的区别,其实用过的人都知道,Java有原生的API可用于发送HTTP请求,即java.net.URL、java.net....

wjxbj的博客 621

HttpURLConnection和httpclient比较

<br /> A Comparison of java.net.URLConnection and HTTPClient<br />Since java.net.URLConnection and HTTPClient have overlapping functionalities, the question arises of why would you use HTTPClient. Here are a few of the capabilites and tradeoffs.<br />Note

dj4kobe的专栏 6535

A Comparison of java.net.URLConnection and HTTPClient

A Comparison of java.net.URLConnection and HTTPClient Since java.net.URLConnection and HTTPClient have overlapping functionalities, the question arises of why would you use HTTPClient. Here are a f

fyfcauc的专栏 545

java发送http请求的方法

项目中经常使用发送http请求,这里总结下java实现的几种方式: 1.HttpURLConnection 使用JDK原生提供的net,无需其他jar包; HttpURLConnection是URLConnection的子类,提供更多的方法,使用更方便。 package httpURLConnection; import java.io.BufferedReader; import ja...

香槟的博客 915
上一篇: Android4.0 Launcher拖拽原理分析
下一篇: Android launcher3布局和结构
cding1818
博客等级 码龄17年 963粉丝 154原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址