package com.zjw.mynetwork2;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
//9.2 p314 使用HTTP协议访问网络
//HTTP大致工作原理:客户端发出一条HTTP请求 服务端收到请求返回有些数据 客户端对返回的数据进行解析和处理
//9.2.1 p315 使用HttpURLConnection
/*
Android上发送HTTP请求一般有两种方式:HttpURLConnection、HttpClient
HttpUrlConnection:jdk提供的标准类,简单,轻量级,容易扩展;
在 android 2.3之前的版本,存在一些明显的bug:比如关闭输入流时,可能导致连接池失效;
Android 2.3版本中增加了一些HTTPS、数据压缩和会话的机制方面作了改进,能更加高效地连接服务器;
Android4.0添加了响应缓存机制;
Android4.4开始底层改用OKHTTP实现;
HttpClient: Api丰富,功能较强,bug很少,但较难扩展;Android 6.0 谷歌把它从sdk中移除了。
两者如何选择?
(1)对于Android 2.3之前版本,选择HttpClient, 它的bug很少而HttpURLConnection有明显的bug;
(2)而对于Android 2.3及以后的版本,选择使用HttpURLConnection;
它的API简单,体积较小,易扩展,适合Android项目。
压缩和缓存机制可以有效地减少网络访问的流量,在提升速度和省电方面也起到了较大的作用。
*/
/*
HttpURLConnection用法步骤:
1.获取HttpURLConnection实例
一般只要new一个URL对象,并传入目标网络地址,然后调用一下openConnection()方法。代码:
URL url=new URL(http://www.baidu.com);
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
2.设置HTTP请求所使用的方法
常用:GET POST
GET:表示希望从服务器获取市局
POST:表示希望提交是数据给服务器
代码:
connection.setRequestMethod("GET");
3.自由定制,比如连接超时,读取超时的毫秒数,服务器希望获取的一些消息头等,例:
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
4.获取服务器返回输入流,调用getInputStream(),对输入流读取解析
InputStream in=connection.getInputStream();
5.关闭HTTP连接
connect.disconnect();
*/
/*
主布局:
LinearLayout
Button:发送HTTP请求
ScrollView:防止内容过多一屏显示不全,可以以滚动形式查看屏幕外的内容
TextView:显示服务器返回数据
*/
//别忘在清单文件中声明网络权限<uses-permission android:name="android.permission.INTERNET"/>
//最终界面上显示的是HTML代码形式存在
/*
提交数据给服务器:
HTTP请求方法改为POST,并在获取输入流之前把要提交的数据写出来
每条数据都已键值对,数据与数据之间用&隔开
代码:
httpURLConnection.setRequestMethod("POST");
DataOutputStream out=new DataOutputStream(httpURLConnection.getOutputStream());
out.writeBytes("username=admin&password=123456");
*/
public class UseOfHttpURLConnection extends AppCompatActivity {
private Button mBtnSendRequest;
private TextView mTvResponseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_use_of_http_urlconnection);
//找到控件
mBtnSendRequest = (Button) findViewById(R.id.btn_send_request);
mTvResponseText = (TextView) findViewById(R.id.tv_response_text);
//Button点击事件,发送HTTP请求
mBtnSendRequest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//用HttpURLConnection发送HTTP请求
sendRequestWithHttpURLConnection();
}
});
}
//用HttpURLConnection发送HTTP请求
private void sendRequestWithHttpURLConnection() {
//开启新线程来发送网络请求
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection httpURLConnection=null;
BufferedReader bufferedReader=null;
try {
URL url=new URL("https://www.baidu.com");//URL对象
httpURLConnection= (HttpURLConnection) url.openConnection();//获取HttpURLConnection实例
httpURLConnection.setRequestMethod("GET");//设置HTTP请求所使用的方法
httpURLConnection.setConnectTimeout(5000);//连接超时的毫秒数
httpURLConnection.setReadTimeout(5000);//读取超时的毫秒数
InputStream inputStream=httpURLConnection.getInputStream();//获取服务器返回输入流
//对从服务器获取到的输入流进行读取解析
bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder=new StringBuilder();
String line;
while ((line=bufferedReader.readLine())!=null){
stringBuilder.append(line);
}
//将数据设置给TextView
showResponse(stringBuilder.toString());
} catch (Exception e) {
e.printStackTrace();
}finally {
if(bufferedReader!=null){//关闭输入流
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(httpURLConnection!=null){//关闭HTTP连接
httpURLConnection.disconnect();
}
}
}
}).start();
}
//将数据设置给TextView
private void showResponse(final String s) {
//在UI线程(主线程)更新UI,因为Android不允许在子线程中进行UI操作
runOnUiThread(new Runnable() {
@Override
public void run() {
mTvResponseText.setText(s);
}
});
}
}
转载于:https://my.oschina.net/u/3620480/blog/1486945
本文深入讲解了使用HTTP协议访问网络的基本原理,对比分析了HttpURLConnection和HttpClient两种方式的优缺点,详细介绍了HttpURLConnection的使用步骤,包括实例创建、请求方法设置、超时设置、输入流读取和连接关闭。
849

被折叠的 条评论
为什么被折叠?



