Http请求的 HttpURLConnection 和 HttpClient
HTTP 请求方式: GET和POST的比较
请求包.png
例子.png
响应包.png
例子.png
请求头描述了客户端向服务器发送请求时使用的http协议类型,所使用的编码,以及发送内容的长度,等等。
相应的响应头用来描述服务器回给你对所返回的content的一些描述,服务器类型,我返回的编码,我返回的内容有多长等等。
原文链接:http://www.jianshu.com/p/42a396430be5
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
- GET请求能够被缓存
- GET请求会保存在浏览器的浏览记录中
- 以GET请求的URL能够保存为浏览器书签
- GET请求有长度限制
- GET请求主要用以获取数据
- POST请求不能被缓存下来
- POST请求不会保存在浏览器浏览记录中
- 以POST请求的URL无法保存为浏览器书签
- POST请求没有长度限制
| GET | POST | |
| 点击返回/刷新按钮 | 没有影响 | 数据会重新发送(浏览器将会提示用户“数据被从新提交”) |
| 添加书签 | 可以 | 不可以 |
| 缓存 | 可以 | 不可以 |
| 编码类型(Encoding type) | application/x-www-form-urlencoded |
application/x-www-form-urlencoded or multipart/form-data. 请为二进制数据使用multipart编码
|
| 历史记录 | 有 | 没有 |
| 长度限制 | 有 | 没有 |
| 数据类型限制 | 只允许ASCII字符类型 | 没有限制。允许二进制数据 |
| 安全性 | 查询字符串会显示在地址栏的URL中,不安全,请不要使用GET请求提交敏感数据 | 因为数据不会显示在地址栏中,也不会缓存下来或保存在浏览记录中,所以看POST求情比GET请求安全,但也不是最安全的方式。如需要传送敏感数据,请使用加密方式传输 |
| 可见性 | 查询字符串显示在地址栏的URL中,可见 | 查询字符串不会显示在地址栏中,不可见 |
其他HTTP请求方式
| 方式 | 描述 |
| HEAD | 与GET请求类似,不同在与服务器只返回HTTP头部信息,没有页面内容 |
| PUT | 上传指定URL的描述 |
| DELETE | 删除指定资源 |
| OPTIONS | 返回服务器支持的HTTP方法 |
| CONNECT | 转换为透明TCP/IP隧道的连接请求 |
1.概念
HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。在 JDK 的 java.net 包中已经提供了访问 HTTP 协议的基本功能:HttpURLConnection。但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。
除此之外,在Android中,androidSDK中集成了Apache的HttpClient模块,用来提供高效的、最新的、功能丰富的支持 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. |
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.案例
1.HttpURLConnection连接URL
1)创建一个URL对象
URL url = new URL(http://www.baidu.com);
2)利用HttpURLConnection对象从网络中获取网页数据
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
3)设置连接超时
conn.setConnectTimeout(6*1000);
4)对响应码进行判断
if (conn.getResponseCode() != 200) //从Internet获取网页,发送请求,将网页以流的形式读回来
throw new RuntimeException("请求url失败");
5)得到网络返回的输入流
InputStream is = conn.getInputStream();
6)String result = readData(is, "GBK"); //文件流输入出文件用outStream.write
7)conn.disconnect();
总结:
--记得设置连接超时,如果网络不好,Android系统在超过默认时间会收回资源中断操作.
--返回的响应码200,是成功.
--在Android中对文件流的操作和JAVA SE上面是一样的.
--在对大文件的操作时,要将文件写到SDCard上面,不要直接写到手机内存上.
--操作大文件是,要一遍从网络上读,一遍要往SDCard上面写,减少手机内存的使用.这点很重要,面试经常会被问到.
--对文件流操作完,要记得及时关闭.
2.向Internet发送请求参数
步骤:
1)创建URL对象:URL realUrl = new URL(requestUrl);
2)通过HttpURLConnection对象,向网络地址发送请求
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
3)设置容许输出:conn.setDoOutput(true);
4)设置不使用缓存:conn.setUseCaches(false);
5)设置使用POST的方式发送:conn.setRequestMethod("POST");
6)设置维持长连接:conn.setRequestProperty("Connection", "Keep-Alive");
7)设置文件字符集:conn.setRequestProperty("Charset", "UTF-8");
8)设置文件长度:conn.setRequestProperty("Content-Length", String.valueOf(data.length));
9)设置文件类型:conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
10)以流的方式输出.
总结:
--发送POST请求必须设置允许输出
--不要使用缓存,容易出现问题.
--在开始用HttpURLConnection对象的setRequestProperty()设置,就是生成HTML文件头.
3.向Internet发送xml数据
XML格式是通信的标准语言,Android系统也可以通过发送XML文件传输数据.
1)将生成的XML文件写入到byte数组中,并设置为UTF-8:byte[] xmlbyte = xml.toString().getBytes("UTF-8");
2)创建URL对象,并指定地址和参数:URL url = new URL(http://localhost:8080/itcast/contanctmanage.do?method=readxml);
3)获得链接:HttpURLConnection conn = (HttpURLConnection) url.openConnection();
4)设置连接超时:conn.setConnectTimeout(6* 1000);
5)设置允许输出conn.setDoOutput(true);
6)设置不使用缓存:conn.setUseCaches(false);
7)设置以POST方式传输:conn.setRequestMethod("POST");
8)维持长连接:conn.setRequestProperty("Connection", "Keep-Alive");
9)设置字符集:conn.setRequestProperty("Charset", "UTF-8");
10)设置文件的总长度:conn.setRequestProperty("Content-Length", String.valueOf(xmlbyte.length));
11)设置文件类型:conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
12)以文件流的方式发送xml数据:outStream.write(xmlbyte);
总结:
--我们使用的是用HTML的方式传输文件,这个方式只能传输一般在5M一下的文件.
--传输大文件不适合用HTML的方式,传输大文件我们要面向Socket编程.确保程序的稳定性
--将地址和参数存到byte数组中:byte[] data = params.toString().getBytes();
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();
}
Http请求的 HttpURLConnection 和 HttpClient的更多相关文章
- 关于安卓HTTP请求用HttpUrlConnection还是HttpClient好
安卓和JAVA应用开发少不了要提交HTTP请求,而基本上目前有两个实现方式:HttpUrlConnection(即URL.openConnection)和HttpClient. 网上不少人都认为Htt ...
- Android HTTP请求用HttpUrlConnection与HttpClient比较
在安卓和JAVA应用开发中需要访问网络,少不了要提交HTTP请求,而基本上目前有两个实现方式:HttpUrlConnection(即URL.openConnection)和HttpClient. 网上 ...
- android 中的Http请求类HttpUrlConnection和HttpClient类
Android系统提供了两种HTTP通信类,HttpURLConnection和HttpClient. 如何选择这两个类的使用:android-developers.blogspot.com/2011 ...
- android菜鸟学习笔记24----与服务器端交互(一)使用HttpURLConnection和HttpClient请求服务端数据
主要是基于HTTP协议与服务端进行交互. 涉及到的类和接口有:URL.HttpURLConnection.HttpClient等 URL: 使用一个String类型的url构造一个URL对象,如: U ...
- java 的http请求方式:HttpURLConnection和HttpClient
1.要了解一些概念性的东西,比如Http的协议以及协议头等一些东东 2.HttpURLConnection一般步骤:创建URL对象==>获取URL的HttpURLConnection对象实例== ...
- Android入门(二十)HttpURLConnection与HttpClient
原文链接:http://www.orlion.ga/679/ 在 Android上发送 HTTP请求的方式一般有两种,HttpURLConnection和 HttpClient. 一.HttpURLC ...
- Android HttpURLConnection And HttpClient
Google的工程师的一个博客写到: HttpURLConnection和HttpClient Volley HTTP请求时:在Android 2.3及以上版本,使用的是HttpURLConnecti ...
- android 网络编程之HttpURLConnection与HttpClient使用与封装
1.写在前面 大部分andriod应用需要与服务器进行数据交互,HTTP.FTP.SMTP或者是直接基于SOCKET编程都可以进行数据交互,但是HTTP必然是使用最广泛的协议. 本文并 ...
- Android --http请求之HttpURLConnection
参考博客:Android HttpURLConnection 基础使用 参考博客:Android访问网络,使用HttpURLConnection还是HttpClient? String getUrl ...
随机推荐
- linux 第二天
文件权限和用户组 groupadd 组名 groupadd policeman 查看组 vi /etc/group cat /etc/group 创建用户,并同时指定将该用户分配到哪个组 userad ...
- 用CALayer实现淡入淡出的切换图片效果
由于直接更改layer的contents显示的隐式动画切换的时候的动画持续时间没办法控制, 切换效果不尽人意,所以这里配合了CABasicAnimation实现淡入淡出的切换效果, 另外还可以使用组合 ...
- preventDefault() 方法 取消掉与事件关联的默认动作
前几天写的 响应键盘的图片切换 中, 键盘总是让浏览器滚动,为了取消掉默认的事件,使用了 preventDefault() 方法 定义和用法 preventDefault() 方法取消事件的默认动作. ...
- CSS块级元素与行级元素(转载)
块元素一般都从新行开始,它可以容纳内联元素和其他块元素,常见块元素是段落标签'P".“form"这个块元素比较特殊,它只能用来容纳其他块元素. 如果没有css的作用,块元素会顺序以 ...
- stax解析XML-----Demo
Demo public void staxDemo() throws Exception { XMLStreamReader xml= XMLInputFactory.newInstance().cr ...
- CSS布局注意(纯属个人总结)
和CSS样式有关多用class,和后台数据有关多用id. 1.使用绝对定位时(偏移量如:top,left...),如果父类没有相对定位,使用绝对定位的元素是相对根元素(即<html>标签) ...
- 查找Mysql数据库连接jar包和对应的Driver和Url
以前写jdbc连接向来都是直接copy,对于连接数据库的jar包在哪下载,对应的Driver类是哪一个,数据库连接串怎么找等等都没有做过,今天从零开始整了一遍. 使用的数据库是Mysql 一.已安装了 ...
- mysql-1862、1820、java.sql.SQLException: Your password has expired. To log in you must change it using a client that supports expired passwords.
之前一直运行的好好的,突然mysql就无法工作了.请求命令后报错误:ERROR 1820 (HY000): You must SET PASSWORD before executing this st ...
- Symfony2 是什么(转)
本文转自:http://www.cnblogs.com/Seekr/archive/2012/06/15/2550894.html Symfoy2 是什么? PHP世界里又一广受关注的web MVC框 ...
- OpenStack虚机相关错误
OpenStack配置起来还是挺麻烦的,特别是网络那块.虽然官方文档越来越清晰,但有时还是会出各种错.排错主要是看日志.看官方文档和google 以下就一些虚机相关常见的错误做一下总结(基于Iceho ...