HTTP通信原理
HTTP(HyperText Transfer Protocol)是客户端与服务器之间的应用层协议,基于请求-响应模型,安卓通过发送HTTP请求(如GET、POST)与服务器交互,服务器返回HTML、JSON等格式的数据。
安卓网络权限配置
在AndroidManifest.xml
中声明网络权限:
<uses-permission android:name="android.permission.INTERNET" />
HttpURLConnection
发送请求// 示例:发送GET请求 URL url = new URL("https://example.com/api/data"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); int responseCode = connection.getResponseCode(); if (responseCode == 200) { // 读取输入流 InputStream inputStream = connection.getInputStream(); // 处理数据(如解析JSON) }
安卓主线程禁止执行网络操作,需通过以下方式处理:
AsyncTask
(已弃用,建议新项目用其他方案)
new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... voids) { // 执行网络请求 return "result"; } @Override protected void onPostExecute(String result) { // 更新UI } }.execute();
Retrofit
(推荐)
Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://example.com/") .addConverterFactory(GsonConverterFactory.create()) .build(); MyApiService service = retrofit.create(MyApiService.class); Call<MyResponse> call = service.getData(); call.enqueue(new Callback<MyResponse>() { @Override public void onResponse(Call<MyResponse> call, Response<MyResponse> response) { // 处理响应 } @Override public void onFailure(Call<MyResponse> call, Throwable t) { // 处理失败 } });
数据格式 | 解析方式 | 示例库 |
---|---|---|
JSON | Gson 、Jackson 、org.json |
Gson 最常用 |
XML | XmlPullParser 、Simple |
较少使用 |
PLAIN | InputStream 直接读取 |
简单文本 |
JSON解析示例(Gson):
String json = "{"name":"John", "age":30}"; Gson gson = new Gson(); Person person = gson.fromJson(json, Person.class);
现象:应用崩溃,提示NetworkOnMainThreadException
。
解决:检查AndroidManifest.xml
是否添加<uses-permission android:name="android.permission.INTERNET" />
。
原因:服务器使用自签名证书或证书不受信任。
解决:绕过证书验证(仅限测试环境):
connection.setSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault()); connection.setHostnameVerifier((hostname, session) -> true);
步骤 | 客户端(Retrofit) | 服务器(假设REST API) |
---|---|---|
定义接口 | @POST("/login") Call<LoginResponse> login(@Body LoginRequest request) |
POST /login ,接收用户名密码 |
发送请求 | service.login(new LoginRequest("user", "pass")).enqueue(callback) |
返回200 OK 和Token |
处理响应 | 存储Token到SharedPreferences |
{ "token": "abc123" } |
解答:使用TypeToken
或List
泛型解析。
String jsonArray = "[{"name":"A"}, {"name":"B"}]"; List<Person> list = new Gson().fromJson(jsonArray, new TypeToken<List<Person>>(){}.getType());
解答: