HttpURLConnection可以發起網絡請求,比如說我們需要從服務器獲取數據
一、layout佈局
方便起見,就放一個button就行了
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
tools:context=".MainActivity">
<Button
android:id="@+id/btn_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="請求"/>
</LinearLayout>
二、Java代碼
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Button btn_send;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_send = findViewById(R.id.btn_send);
btn_send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startHttpURLConnection();
}
});
}
private void startHttpURLConnection(){
//耗時操作必須要放在子線程
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();//打開openConnection鏈接
connection.setRequestMethod("GET");//以GET方式發起請求(默認)
/*//若是以POST方式提交數據
connection.setRequestMethod("POST");
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes("usename=name&password=111111");//提交的數據用&分割 */
connection.setConnectTimeout(5000);//設置請求超時時間爲5秒
connection.setReadTimeout(5000);//設置讀取超時時間爲5秒
InputStream inputStream = connection.getInputStream();//獲得數據流
reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null){
response.append(line);
}
dealWithResult(response.toString());//新建一個方法處理請求得到的數據
}catch (Exception e){e.printStackTrace();}
finally {
if (reader != null){
try{reader.close();}catch (Exception e){e.printStackTrace();}
}
if(connection != null){
connection.disconnect();
}
}
}
}).start();
}
private void dealWithResult(final String res){
}
}
三、更新UI線程
方法一:
private void dealWithResult(final String res){
//在UI主線程操作,比如說用TextView顯示
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.e("res", "dealWithResult: "+res);
}
});
}
方法二:
private void dealWithResult(final String res){
//在UI主線程操作,比如說用TextView顯示
new Handler(getApplicationContext().getMainLooper()).post(new Runnable() {
@Override
public void run() {
Log.e("res", "run: "+res );
}
});
}
四、添加網絡權限
在Androidmanifest中使用權限
<uses-permission android:name="android.permission.INTERNET"/>
若是Android 9或以上,還需要在application標籤中加入
android:usesCleartextTraffic="true"