HTTP请求
HTTP请求是客户端与服务端之间发送请求和返回应答的标准(TCP);
客户端发出一个HTTP请求之后,就与服务器建立起TCP连接,服务器接收到请求后并进行处理后返回给客户端响应数据。
HTTP请求方式
- get()方式属于明文传参,在地址栏可以看到参数,调用简单,不安全;
- post()方式输入暗文传参,在地址栏参数不可见,调用稍微复杂,安全。
HttpUrlConnection
HttpUrlConnection对象:
URL url=new URL("https://www.baidu.com");
//openConnect
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
//inputStream
InputStream inputStream=httpURLConnection.getInputStream();
注意
1、在Android中访问网络必须添加网络权限
<uses-permission android:name="android.permission.INTERNET" />
2、在Android中访问网络必须放在子线程中执行
使用HTTPUrlConnection步骤
HttpUrlConnection发送GET请求的步骤:
- 创建URL对象;
- 通过URL对象调用onpenConnection()方法获得HttpUrlConnection对象;
- HttpUrlConnection对象设置其他连接属性;
- HttpUrlConnection对象调用getInputStream()方法向服务器发送HTTP请求并获取到服务器返回的输入流;
- 读取输入流,转换成String字符串。
使用HTTPUrlConnection获取HTTP请求
layout布局:
<Button
android:layout_width="match_parent"
android:id="@+id/net_btn"
android:text="点击"
android:textSize="30sp"
android:layout_height="wrap_content" />
activity中代码:
public class Main3Activity extends AppCompatActivity {
private Button Btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
Btn=findViewById(R.id.net_btn);
Btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
getWebInfo();
}
}).start();
}
});
}
private void getWebInfo() {
//创建URL
try {
URL url=new URL("https://www.baidu.com");
//openConnect
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
//inputStream
InputStream inputStream=httpURLConnection.getInputStream();
//InputStream
InputStreamReader reader=new InputStreamReader(inputStream,"UTF-8");
//BUfferedReader
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("MAlA", stringBuffer.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}