在Android中,可以使用HttpURLConnection来进行网络请求。下面是一个简单的示例,演示如何使用HttpURLConnection发送GET请求:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new Thread(new Runnable() { @Override public void run() { try { // 创建URL对象 URL url = new URL("http://example.com/api/data"); // 打开连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置请求方法为GET conn.setRequestMethod("GET"); // 设置连接超时时间 conn.setConnectTimeout(5000); // 获取服务器返回的输入流 BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); // 读取服务器返回的数据 StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } // 关闭输入流和连接 reader.close(); conn.disconnect(); // 在主线程中更新UI runOnUiThread(new Runnable() { @Override public void run() { // 处理服务器返回的数据 String result = response.toString(); // 更新UI textView.setText(result); } }); } catch (IOException e) { e.printStackTrace(); } } }).start(); } }
上述代码中,在run()
方法中创建了一个URL对象,然后通过openConnection()
方法打开连接。设置请求方法为GET,连接超时时间为5秒。通过getInputStream()
方法获取服务器返回的输入流,并使用BufferedReader
来读取数据。最后在主线程中更新UI,处理服务器返回的数据。
需要注意的是,网络请求不能在主线程中执行,否则会导致ANR(Application Not Responding)错误。所以我们使用了一个新的线程来执行网络请求。