Android 下使用 JSON 实现 HTTP 请求
封面图
•
2025-11-21
•
Android开发
307
0
0
0
在 Android 开发中,使用 **JSON** 实现 HTTP 请求是一种常见的做法。通常我们会使用 `HttpURLConnection` 或第三方库如 `OkHttp`、`Retrofit` 来发送 HTTP 请求,并使用 `JSONObject` 和 `JSONArray` 来解析 JSON 数据。 下面我将为你展示一个完整的示例:**使用 `HttpURLConnection` 发送 GET 请求并解析 JSON 响应**。 --- ## ✅ 1. 添加网络权限(AndroidManifest.xml) ```xml <uses-permission android:name="android.permission.INTERNET" /> ``` --- ## ✅ 2. 使用 `HttpURLConnection` 发送 GET 请求并解析 JSON ### 示例:获取用户信息(GET 请求) ```java import android.os.AsyncTask; import android.util.Log; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class JsonGetRequest extends AsyncTask<Void, Void, String> { private static final String URL = "https://jsonplaceholder.typicode.com/users/1"; @Override protected String doInBackground(Void... voids) { try { URL url = new URL(URL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); int responseCode = conn.getResponseCode(); Log.d("HTTP", "Response Code: " + responseCode); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder result = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { result.append(line); } reader.close(); return result.toString(); } else { return "Error: " + responseCode; } } catch (Exception e) { e.printStackTrace(); return "Exception: " + e.getMessage(); } } @Override protected void onPostExecute(String result) { super.onPostExecute(result); Log.d("JSON Response", result); try { JSONObject user = new JSONObject(result); String name = user.getString("name"); String email = user.getString("email"); Log.d("User Info", "Name: " + name + ", Email: " + email); } catch (Exception e) { e.printStackTrace(); Log.e("JSON Error", e.getMessage()); } } } ``` --- ## ✅ 3. 在 Activity 中调用这个任务 ```java public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new JsonGetRequest().execute(); } } ``` --- ## ✅ 4. 使用 POST 请求(可选) 如果你需要发送 POST 请求并携带 JSON 数据: ### 示例:发送 JSON 数据(POST 请求) ```java String jsonInputString = "{\"name\":\"John\",\"email\":\"john@example.com\"}"; URL url = new URL("https://jsonplaceholder.typicode.com/users"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json; utf-8"); conn.setRequestProperty("Accept", "application/json"); conn.setDoOutput(true); try (OutputStream os = conn.getOutputStream()) { byte[] input = jsonInputString.getBytes("utf-8"); os.write(input, 0, input.length); } int responseCode = conn.getResponseCode(); // 处理响应... ``` --- ## ✅ 5. 推荐的第三方库(更简洁) 如果你不想手动处理网络请求,可以使用以下库: ### ✅ OkHttp(推荐) 添加依赖: ```gradle implementation 'com.squareup.okhttp3:okhttp:4.12.0' ``` 示例代码: ```java OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("https://jsonplaceholder.typicode.com/users/1") .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { String jsonData = response.body().string(); Log.d("JSON Response", jsonData); try { JSONObject user = new JSONObject(jsonData); String name = user.getString("name"); String email = user.getString("email"); runOnUiThread(() -> Toast.makeText(MainActivity.this, "Name: " + name, Toast.LENGTH_SHORT).show()); } catch (JSONException e) { e.printStackTrace(); } } }); ``` --- ## ✅ 总结 | 功能 | 方法 | |------|------| | 发送 GET 请求 | `HttpURLConnection` / `OkHttp` | | 发送 POST 请求 | `HttpURLConnection` / `OkHttp` | | 解析 JSON | `JSONObject`, `JSONArray` | | 网络权限 | `android.permission.INTERNET` | --- 如果你有具体需求(比如上传文件、处理复杂 JSON、使用 Retrofit 等),也可以告诉我,我可以提供更详细的示例。
上一篇:
android上传图片至服务器
下一篇:
Android 控件ProgressBar进度条
标题录入,一次不能超过6条
留言
评论