This article directory
Android native currently supports two ways to access the http protocol network, the first one is HttpURLConnection
, the other is oKHttp
, let's introduce 用HttpURLConnection
the method to access the http protocol
Step 1: Add network access
AndroidManifest.xml
Add the following permissions in the file
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
http request requires AndroidManifest.xml
the file application
and add the following property nodes
android:usesCleartextTraffic="true"
Step 2: Use HttpURLConnection to access the network
First of all we need to get HttpURLConnection
the instance, HttpURLConnection
the method of obtaining is as follows
URL url = new URL("http://baidu.com");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
After getting an instance of HttpURLConnection, we can use HttpURLConnection
the instance to set some HTTP request methods
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(8000);
urlConnection.setRequestProperty("key","value");
Method name | meaning |
---|---|
setRequestMethod | Request method (common include GET and POST, etc.) |
setConnectTimeout | Request timeout |
setRequestProperty | The parameters in the request |
After the request is sent, we can HttpURLConnection
get the returned data of the request through the instance
InputStream inputStream = urlConnection.getInputStream();// 字节流
Reader reader = new InputStreamReader(inputStream);//字符流
BufferedReader bufferedReader = new BufferedReader(reader);// 缓存流
Then we can bufferedReader
read data from the cache stream
StringBuilder result = new StringBuilder();;
String temp;
while ((temp = bufferedReader.readLine()) != null) {
result.append(temp);
}
Log.i("MainActivity", result.toString());
Don't forget to close the data stream after reading the data
if (reader!=null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bufferedReader!=null){
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (urlConnection != null){
urlConnection.disconnect();
}
We also need to put in the child thread to access the network request
new Thread(){
@Override
public void run() {
super.run();
getNetwork();
}
}.start();
Cut the obtained data into the main thread and display it with text
runOnUiThread(new Runnable() {
@Override
public void run() {
mTextView.setText(result);
}
});
Code example
The complete code is as follows
MainActivity.java
package com.lucashu.http;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
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.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
mTextView = findViewById(R.id.textView);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(){
@Override
public void run() {
super.run();
getNetwork();
}
}.start();
}
});
}
private void getNetwork() {
InputStream inputStream = null;
Reader reader = null;
BufferedReader bufferedReader = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL("http://baidu.com");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(8000);
urlConnection.setRequestProperty("key","value");
inputStream = urlConnection.getInputStream();// 字节流
reader = new InputStreamReader(inputStream);//字符流
bufferedReader = new BufferedReader(reader);// 缓存流
final StringBuilder result = new StringBuilder();;
String temp;
while ((temp = bufferedReader.readLine()) != null) {
result.append(temp);
}
Log.i("MainActivity", result.toString());
runOnUiThread(new Runnable() {
@Override
public void run() {
mTextView.setText(result);
}
});
inputStream.close();
reader.close();
bufferedReader.close();
} catch (Exception e) {
Log.i("MainActivity", e.getMessage());
e.printStackTrace();
}finally {
if (reader!=null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bufferedReader!=null){
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (urlConnection != null){
urlConnection.disconnect();
}
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.lucashu.http">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:usesCleartextTraffic="true">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.323" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="96dp"
android:text="访问网络数据"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>