一、概述
在使用Http协议访问网络时,对于HTTP协议,我们只需要了解他的工作原理就OK了。
HTTP工作原理:客户端向服务器发出一条HTTP请求,服务器收到请求之后会返回一些数据给客户端,然后客户端再对这些数据进行解析和处理就可以了。
Http常用的请求方式
1.get方式属于明文传参,在地址栏可以看到参数,调用简单,不安全。(表示希望从服务器那里获取数据)
2.post方式输入暗文传参,在地址栏参数不可见,调用稍复杂,安全。(表示希望提交数据给服务器)
二、HttpURLConnection的使用
如何使用HttpURLConnection发送GET请求的步骤
1.创建URL对象2.通过URL对象调用openConnection()方法获得HttpURLConnection对象
URL url=new URL("https://www.baidu.com");
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
3.HttpURLConnection对象设置其他连接属性
connection.setRequestMethod("GET");//设置HTTP请求方式为GET
connection.setConnectTimeout(8000);//设置连接超时的毫秒数
connection.setReadTimeout(8000);//设置读取超时的毫秒数
4.HttpURLConnection对象调用getInputStream()方法向服务器发送http请求 并获取到服务器返回的输入流
InputStream in=connection.getInputStream();
//下面对获取到的输入流进行读取
BufferedReader reader=new BufferedReader(new InputStreamReader(in));
StringBuilder response=new StringBuilder();
String line;
while ((line=reader.readLine())!=null){
response.append(line);
}
5.读取输入流,转换成String字符串
注:不要忘记加权限
<uses-permission android:name="android.permission.INTERNET"/>
发送post请求时,只需要将HTTP请求的方式改成POST,并在获取输入流之前把要提交的数据写出即可。
注意每条数据都要以键值对的形式存在,数据与数据之间用“&”符号隔开,比如向服务器提交用户名和密码
connection.setRequestMethod("POST");
DataOutputStream out=new DataOutputStream(connection.getOutputStream());
out.writeBytes("username=admin&password=123456");
下面写一个实例,点击一个按钮之后在TextView中显示请求百度返回的数据
编写xml代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.lk.networktest.MainActivity">
<Button
android:id="@+id/send_request"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send Request" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/response_text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
编写activity中的代码
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
TextView responseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendRequest= (Button) findViewById(R.id.send_request);
responseText= (TextView) findViewById(R.id.response_text);
sendRequest.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v.getId()==R.id.send_request){
sendRequestWithHttpURLConnection();
}
}
private void sendRequestWithHttpURLConnection() {
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection=null;
BufferedReader reader=null;
try {
URL url=new URL("https://www.baidu.com");
connection= (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");//设置HTTP请求方式为GET
connection.setConnectTimeout(8000);//设置连接超时的毫秒数
connection.setReadTimeout(8000);//设置读取超时的毫秒数
InputStream in=connection.getInputStream();
//下面对获取到的输入流进行读取
reader=new BufferedReader(new InputStreamReader(in));
StringBuilder response=new StringBuilder();
String line;
while ((line=reader.readLine())!=null){
response.append(line);
}
showResponse(response.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(reader!=null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection!=null){
connection.disconnect();
}
}
}
}).start();
}
private void showResponse(final String s) {
runOnUiThread(new Runnable() {
@Override
public void run() {
//在这里进行UI操作,将结果显示到界面上
responseText.setText(s);
}
});
}
}
3.声明权限
<uses-permission android:name="android.permission.INTERNET"/>