import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class NetworkRequestDemo extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String result = null;
try {
URL url = new URL("http://www.example.com/api/data");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder buffer = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line).append("n");
}
result = buffer.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (result != null) {
Log.d("NetworkRequestDemo", "Result: " + result);
}
return null;
}
}
使用方法如下:
NetworkRequestDemo networkRequestDemo = new NetworkRequestDemo();
networkRequestDemo.execute();
这里是一个简单的 Android 网络请求的示例代码,使用 OkHttp 库发送 GET 请求获取数据:
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class NetworkRequestDemo {
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://jsonplaceholder.typicode.com/posts/1")
.build();
try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
String responseData = response.body().string();
System.out.println(responseData);
} else {
System.out.println("请求失败: " + response.code());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
这段代码发送一个 GET 请求到 JSONPlaceholder 的测试 API,获取 ID 为 1 的帖子的数据,并将响应打印输出。请注意需要在 Android 项目中添加 OkHttp 的依赖。
希望能帮到您,如有其他问题,请随时提出。
发布者:luotuoemo,转转请注明出处:https://www.jintuiyun.com/153074.html