代码示例,另外清单文件记得添加网络权限
public class NetWorkActivity extends AppCompatActivity implements View.OnClickListener { private TextView showDatas; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_net_work); initView(); } private void initView() { showDatas = ((TextView) findViewById(R.id.showDatas)); findViewById(R.id.getNetData).setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.getNetData: sendGetRequest(); break; } } // 发送get请求 private void sendGetRequest() { // 网络请求属于耗时操作,必须开线程 new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection = null; BufferedReader read = null; try { URL url = new URL("https://www.baidu.com"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(8000); connection.setReadTimeout(8000); InputStream in = connection.getInputStream(); // 用bufferreader对请求到的数据进行读取 read = new BufferedReader(new InputStreamReader(in)); StringBuilder builder = new StringBuilder(); String line; while ((line = read.readLine()) != null) { builder.append(line); } showData(builder.toString()); } catch (Exception e) { e.printStackTrace(); } } }).start(); } private void showData(final String msg) { // android不允许在在子线程进行ui操作,通过runOnUiThread将线程切换到 // 主线程,再更新UI元素。 runOnUiThread(new Runnable() { @Override public void run() { showDatas.setText(msg); } }); } // 发送post请求 private void sendPostRequest() { new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection = null; BufferedReader read = null; try { URL url = new URL("https://www.baidu.com"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setConnectTimeout(8000); connection.setReadTimeout(8000); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); // 传送的数据以键值对形式数据之间用&分隔 out.writeBytes("username = admin&password=123456"); InputStream in = connection.getInputStream(); // 用bufferreader对请求到的数据进行读取 read = new BufferedReader(new InputStreamReader(in)); StringBuilder builder = new StringBuilder(); String line; while ((line = read.readLine()) != null) { builder.append(line); } showData(builder.toString()); } catch (Exception e) { e.printStackTrace(); } } }).start(); } }