android如何从服务器获得数据
在Android中,可使用HTTP要求来从服务器获得数据。以下是一种常见的方法:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public String sendHttpRequest(String urlStr) throws IOException {
StringBuilder response = new StringBuilder();
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
return response.toString();
}
new Thread(new Runnable() {
@Override
public void run() {
try {
String url = "http://your_server_url.com/data";
String response = sendHttpRequest(url);
// 在这里处理服务器返回的数据
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
在这个例子中,我们使用了一个简单的GET要求来获得服务器的数据。你需要将http://your_server_url.com/data
替换为你的实际服务器地址和路径。
请注意,由于网络要求触及到网络操作,不建议在主线程中履行。你应当将网络要求放在单独的线程中,还是使用异步任务(AsyncTask)来履行。
TOP