您的位置:首页 > 理论基础 > 计算机网络

【转】 Pro Android学习笔记(七二):HTTP服务(6):HttpURLConnection

2015-12-15 13:44 597 查看
目录(?)[-]

Http Get的使用方式

基础小例子

Cookie的使用

重定向

HTTP POST的小例子

基础小例子

文章转载只能用于非商业性质,且不能带有虚拟货币、积分、注册等附加条件,转载须注明出处:http://blog.csdn.net/flowingflying/

之前我们都是使用HttpClient来进行http连接,在上一次学习中,HttpClient远比封装socket要来得复杂,有管理器,有连接池。从Android2.3版本开始,可以是java.net.HttpURLConnection提供更小更轻载的连接服务。具体详见:http://developer.android.com/reference/java/net/HttpURLConnection.html

Http Get的使用方式

基础小例子

private void httpUrlConnGetTest(){
HttpURLConnection urlConn = null;
try{
URL url = new URL("http://www.android.com/");

/* 【1】 获取HttpURLConnection的对象。通过调用URL.openConnection(),并将类型适配为HttpURLConnection类型。 如果是处理https,则使用HttpsURLConnecction,相关的代码参考: http://developer.android.com/reference/javax/net/ssl/HttpsURLConnection.html */
urlConn = (HttpURLConnection) url.openConnection();

/* 【2】 处理request的header,设置超时属性 。 */
urlConn.setRequestProperty("private-Hello", "Hello world!");//加入属性测试
urlConn.setConnectTimeout(3000); //对应connection timeout
urlConn.setReadTimeout(5000); //对应Socket timeout

/* 【3】 处理request的body。HTTP Get 没有body,相关的在HTTP POST中演示 */

/* 【4】读取response。*/
// 【4.1】获取response code测试
int responseCode = urlConn.getResponseCode();
Log.d("PRO","Response code = " + responseCode);
if(responseCode == HttpURLConnection.HTTP_OK){
Log.d("PRO","测试获取头信息Content-Type:" + urlConn.getContentType()); //【4.2】获取header信息测试
// 读取body
BufferedReader in = new BufferedReader(
new InputStreamReader(
urlConn.getInputStream()));
String line = null;
while((line = in.readLine()) != null ){
Log.d("PRO",line);
}
in.close();
}
}catch(Exception e){
e.printStackTrace();
}finally{
/* 【5】 断开连接。*/
if(urlConn != null)
urlConn.disconnect();
}
}



HttpURLConnection看起来真整个设计更贴近底层的TCP的流概念。从抓包情况看,已经成功地增加自定义的头字段:private-Hello: Hello world!。我们可以根据所需属性,构造http请求消息。HttpURLConnectoion也支持401的认证,不过现在基本上很少用这种认证方式,SIP还在用。

Cookie的使用

// 通过CookieHander和CookieManager,HttpURLConnection包含一个格外的cookie管理器,以此在client和server件维护一个长期的session。这部分的代码来自reference。
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
//写和读cookie的小例子
HttpCookie cookie = new HttpCookie("lang", "fr");
cookie.setDomain("twitter.com");
cookie.setPath("/");
cookie.setVersion(0);
cookieManager.getCookieStore().add(new URI("http://twitter.com/"), cookie);

重定向

HttpURLConnection可以自动处理重定向的情况,对代码进行修改来进行相关测试。HttpURLConnection最多可支持5次重定向(估计是防止循环),但不能跨scheme,即不能重http重定向到https,反之亦然,原因很简单,因为http和https是由不同的类来进行处理。当然浏览器是支持跨scheme的重定向。HttpURLConnection会自动根据302 Found消息给出的Location信息进行连接。

URL url = new URL("http://www.google.com/"); //将被重定向到www.google.com.hk
... ...
/* 4、读取response */
if(!url.getHost().equals(urlConn.getURL().getHost())) //比较请求的url和实际的url
Log.d("PRO","Redirect to " + urlConn.getURL().getHost());
… …

HTTP POST的小例子

基础小例子

如果设置了setDoOutput(true),这说明是HTTP POST。如果是其他的,例如OPTIONS,HEAD,PUT,DELETE和TRACE,可以通过setRequestMethod(String)来进行设置,无非就是确定status line如何写。

private void httpUrlConnPostTest(){
HttpURLConnection urlConn = null;
try{
URL url = new URL("http://blog.csdn.net/flowingflying1");//这是个无效的地址,预计回复403
urlConn = (HttpURLConnection) url.openConnection();

/* 【3】 处理request的body */
urlConn.setDoOutput(true);
// 设置允许output,即可以带有request body
// 为了性能更好,应该设置setFixedLengthStreamingMod(int)或者setChunkedStramingMode(int)。如果不设置,request将的带buffer已经完成body的写,再发送,这对body数据量大的情况下显然效率较低。
urlConn.setChunkedStreamingMode(0);
// 通过outstream,写入body
OutputStream out = new BufferedOutputStream(urlConn.getOutputStream());
String content = "user=myfriend&action=TEST";
out.write(content.getBytes());
out.close();

/* 4、读取response。*/
if(urlConn.getResponseCode() = HttpURLConnection.HTTP_OK){
BufferedReader in = new BufferedReader(
new InputStreamReader(
urlConn.getInputStream()));
String line = null;
while((line = in.readLine()) != null ){
Log.d("PRO",line);
}
in.close();
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(urlConn != null)
urlConn.disconnect();
}
}

本博文涉及的例子代码,可以在Pro Android学习:Http service小例子中下载。

相关链接: 我的Android开发相关文章
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: