一、HTTP请求的含义
- HTTP请求是客户端和服务端之间,发送请求和返回应答的标准(TCP);
- 客户端发出一个HTTP请求后,就与服务器建立起了TCP连接,服务端接受到请求并进行处理后返回给客户端相应数据。
注意点:HTTP常用的请求方式 get方式和post方式,其中get方式属于明文传参,不安全;post方式属于暗文传参,安全
二、HttpUrlConnection的含义
HttpUrlConnection是java的标准指定网站发送GET请求、POST请求类,HttpUrlConnection继承自URLConn,可用于向指定网站发送GET请求、POST请求,HttpUrlConnection在使用上相对简单,并且易于扩展,推荐好用。
三、使用HttpUrlConnection的步骤
- 创建URL对象
- 通过URL对象调用openConnection对象
- HttpUrlConnection对象设置其他连接属性
- HttpUrlConnection对象调用getInputStream()方法向服务器发送http请求并获取到服务器返回的输入流
- 读取输入流,转化成String字符串
注意点:1.在Android中访问网络必须添加网络权限
2.在Android中访问网络必须在子线程中进行
四、使用HttpUrlConnection获取HTTP请求(以访问csdn网站为例)
1.首先在layout布局文件中定义一个Button控件
<Button
android:id="@+id/show_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
2.然后在主体类里定义控件,绑定ID,设置点击事件
private Button showBtn;
private void bindID() {
showBtn=findViewById(R.id.show_btn);
}
3.在方法体里写方法,最后用log.e来测试
public void onClick(View view) {
new Thread(new Runnable() {
@Override
public void run() {
getWebInfo();
}
}).start();
}
});
}
private void getWebInfo() {
try {
// 1.找水源--URL
URL url=new URL("http://www.youkuaiyun.com/");
//2.开水闸--opeanConnection
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
//3.建管道--InputStream
InputStream inputStream=httpURLConnection.getInputStream();
//4.建蓄水池--InputStreamReader
InputStreamReader reader=new InputStreamReader(inputStream,"UTF-8");
//5.水桶盛水--BufferReader
BufferedReader bufferedReader=new BufferedReader(reader);
StringBuffer stringBuffer=new StringBuffer();
String temp=null;
while((temp=bufferedReader.readLine())!=null){
stringBuffer.append(temp);
}
bufferedReader.close();
reader.close();
inputStream.close();
Log.e("MAIN",stringBuffer.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}