Android(安卓)使用 HttpURLConnection 实例
16lz
2021-01-26
直接上干货,实例代码:
import android.annotation.SuppressLint;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.KeyEvent;import android.view.View;import android.widget.TextView;import java.io.BufferedInputStream;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import java.util.Scanner;public class MainActivity extends Activity { private static final String TAG = "MainActivity"; private static final int SHOW_RESPONSE = 0; @SuppressLint("HandlerLeak") private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case SHOW_RESPONSE: String response = (String) msg.obj; TextView textView = MainActivity.this.findViewById(R.id.response_text); if (null != textView) { textView.setText(response); } } super.handleMessage(msg); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { moveTaskToBack(true); } return super.onKeyUp(keyCode, event); } @Override protected void onResume() { super.onResume(); } @Override protected void onDestroy() { super.onDestroy(); } private String readInStream(InputStream in) { Scanner scanner = new Scanner(in).useDelimiter("\\A"); return scanner.hasNext() ? scanner.next() : ""; } public void sendRequestWithHttpURLConnection(View view) { new Thread(new Runnable() { @Override public void run() { HttpURLConnection urlConnection = null; try { URL url = new URL("https://www.baidu.com/"); urlConnection = (HttpURLConnection)url.openConnection(); Message message = new Message(); message.what = SHOW_RESPONSE; message.obj = readInStream(new BufferedInputStream(urlConnection.getInputStream())); handler.sendMessage(message); } catch (IOException e) { e.printStackTrace(); } finally { urlConnection.disconnect(); } } }).start(); }}
布局文件的代码如下:
<?xml version="1.0" encoding="utf-8"?>
本文参考自 《Android 第一行代码》
更多相关文章
- android 扫描包下所有类
- android 代码实现通知 音效和震动
- android日常学习3-23 实现打字游戏
- Android(安卓)Code Review
- android 开发真机测试,无法安装调试解决
- android 源代码下载
- Android(安卓)代码监控apk安装,卸载,替换
- andriod之ContentProvider读取外部存储图片
- Android用Proguard混淆代码遇到的问题