Http请求的 HttpURLConnection 和 HttpClient

HTTP 请求方式: GET和POST的比较

Http请求的 HttpURLConnection 和 HttpClient
请求包.png
Http请求的 HttpURLConnection 和 HttpClient
例子.png
Http请求的 HttpURLConnection 和 HttpClient
响应包.png
Http请求的 HttpURLConnection 和 HttpClient
例子.png

请求头描述了客户端向服务器发送请求时使用的http协议类型,所使用的编码,以及发送内容的长度,等等。

相应的响应头用来描述服务器回给你对所返回的content的一些描述,服务器类型,我返回的编码,我返回的内容有多长等等。

文/srtianxia(简书作者)
原文链接:http://www.jianshu.com/p/42a396430be5
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
GET和POST是HTTP的两个常用方法。
 
什么是HTTP?
超文本传输协议(HyperText Transfer Protocol -- HTTP)是一个设计来使客户端和服务器顺利进行通讯的协议。
HTTP在客户端和服务器之间以request-response protocol(请求-回复协议)工作。
 
GET - 从指定的服务器中获取数据
POST - 提交数据给指定的服务器处理
 
GET方法:
使用GET方法时,查询字符串(键值对)被附加在URL地址后面一起发送到服务器:
/test/demo_form.jsp?name1=value1&name2=value2
特点:
  • GET请求能够被缓存
  • GET请求会保存在浏览器的浏览记录中
  • 以GET请求的URL能够保存为浏览器书签
  • GET请求有长度限制
  • GET请求主要用以获取数据
POST方法:
使用POST方法时,查询字符串在POST信息中单独存在,和HTTP请求一起发送到服务器:
POST /test/demo_form.jsp HTTP/1.1
Host: w3schools.com
name1=value1&name2=value2
特点:
  • POST请求不能被缓存下来
  • POST请求不会保存在浏览器浏览记录中
  • 以POST请求的URL无法保存为浏览器书签
  • POST请求没有长度限制
GET和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. 
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.案例

  

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

Http请求的 HttpURLConnection 和 HttpClient
    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;
}
}
Http请求的 HttpURLConnection 和 HttpClient

HTTPClient

Http请求的 HttpURLConnection 和 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";
}
}
Http请求的 HttpURLConnection 和 HttpClient

servlet端json转化: 

Http请求的 HttpURLConnection 和 HttpClient
        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());
Http请求的 HttpURLConnection 和 HttpClient

android端接收:

Http请求的 HttpURLConnection 和 HttpClient
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();
}
上一篇:HTML5 canvas绘制线条曲线


下一篇:【POJ】1330 Nearest Common Ancestors ——最近公共祖先(LCA)