当前位置:首页 > 行业动态 > 正文

安卓和http服务器通信

安卓通过HttpURLConnection或OkHttp发起HTTP请求,采用异步任务处理网络操作,解析服务器返回的JSON/XML数据,需配置INTERNET权限,支持GET/POST等方法实现数据交互

基础概念与准备

  1. HTTP通信原理
    HTTP(HyperText Transfer Protocol)是客户端与服务器之间的应用层协议,基于请求-响应模型,安卓通过发送HTTP请求(如GET、POST)与服务器交互,服务器返回HTML、JSON等格式的数据。

  2. 安卓网络权限配置
    AndroidManifest.xml中声明网络权限:

    <uses-permission android:name="android.permission.INTERNET" />

实现HTTP请求的步骤

使用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)
}

异步处理网络请求

安卓主线程禁止执行网络操作,需通过以下方式处理:

安卓和http服务器通信

  • 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 GsonJacksonorg.json Gson最常用
XML XmlPullParserSimple 较少使用
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" />

安卓和http服务器通信

HTTPS证书验证失败

原因:服务器使用自签名证书或证书不受信任。
解决:绕过证书验证(仅限测试环境):

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" }

相关问题与解答

问题1:如何在安卓中处理JSON数组?

解答:使用TypeTokenList泛型解析。

String jsonArray = "[{"name":"A"}, {"name":"B"}]";
List<Person> list = new Gson().fromJson(jsonArray, new TypeToken<List<Person>>(){}.getType());

问题2:为什么Retrofit比HttpURLConnection更高效?

解答

  1. 封装性强:Retrofit自动处理连接、转换、缓存等,减少模板代码。
  2. 扩展性:支持OkHttp、RxJava、协程等高级特性。
  3. 错误处理:内置统一的错误回调