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 ...
随机推荐
- Java的native关键字---JAVA下调用其他语言的关键词
今天研究Java基础类库,Object类的时候,发现了一个关键字:native 咦?这是个什么东东?它认识我,我可不认识它! 嘿嘿,没关系,baidu一下. java native关键字 一. 什么是 ...
- PHP防注入转义功能
PHP addslashes() 函数 $str = addslashes('Shanghai is the "biggest" city in China.'); echo($s ...
- X-Y Problem
X-Y Problem 对于X-Y Problem的意思如下: 1)有人想解决问题X2)他觉得Y可能是解决X问题的方法3)但是他不知道Y应该怎么做4)于是他去问别人Y应该怎么做? 简而言之,没有去问怎 ...
- JavaScript中的memorizing技术
今天看<JavaScript>设计模式第七章--工厂模式的时候接触到memorizing技术,简单的说就是对于某个方法,调用它的实例只在第一次调用它的时候才会进行方法中的计算,之后该实例再 ...
- vsftpd 访问 权限控制
vsftpd 重启命令 service vsftpd start|restart|stop vsftpd 关于权限控制,有两个文件分别设置,都会起作用 /etc/vsftpd/user_list / ...
- 创建一个MVC解决方案,添加一个控制器后,运行程序报错:”/"未找到服务器
1.创建一个MVC项目,如图
- BestCoder Round #36 [B] Gunner
题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=5199 先对树的高度排序,然后对每次射击高度二分查找即可,打过之后数目变为0. #include< ...
- 完全教程 Aircrack-ng来PJ---WEP、WPA-PSK--加密利器
恩,先说明一下,本章的内容适用于目前市面所有主流品牌无线路由器或AP如Linksys.Dlink.TPLink.BelKin等.涉及内容包括了WEP加密及WPA-PSK加密的无线网络的破解操作实战. ...
- 一个正整数N,拆成任意个正整数之和,怎样使这些数的乘积最大
网上看到了如标题所示的题目,就开始想如果用程序来算的话,那么它的算法是怎样的. 自己想了半天,第一感觉要用递归, 如先算出 当 n=1 max=1 当 n=2 max=1 当 n=3 max=2 .. ...
- Yii 引入 js和css
//向控制器指定的页面注册新的css文件 Yii::app()->clientScript->registerCssFile(Yii::app()->baseUrl.'/css/my ...