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

安卓和php服务器交互json

安卓通过HttpURLConnection或OkHttp发送JSON数据至PHP服务器,PHP用json_decode解析后处理逻辑,再以JSON格式返回结果,安卓接收后解析并更新UI,实现跨平台数据交互

安卓与PHP服务器JSON交互实现


安卓端发送JSON请求

  1. 构造JSON数据
    使用JSONObject或第三方库(如Gson)构建JSON对象。

    // 使用JSONObject构造简单数据
    JSONObject json = new JSONObject();
    try {
        json.put("username", "testUser");
        json.put("password", "123456");
    } catch (JSONException e) {
        e.printStackTrace();
    }
  2. 建立HTTP连接
    通过HttpURLConnectionOkHttp发送POST请求,设置请求头为application/json

    // 使用HttpURLConnection发送请求
    URL url = new URL("https://example.com/api/login.php");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
    conn.setDoOutput(true);
  3. 发送JSON数据
    将JSON写入请求体并发送。

    安卓和php服务器交互json  第1张

    // 写入JSON到输出流
    try (OutputStream os = conn.getOutputStream()) {
        byte[] input = json.toString().getBytes("UTF-8");
        os.write(input, 0, input.length);
    }

PHP服务器处理JSON请求

  1. 接收并解析JSON
    使用file_get_contents('php://input')获取原始POST数据,再用json_decode解析。

    // login.php示例
    header('Content-Type: application/json; charset=utf-8');
    $rawData = file_get_contents('php://input');
    $data = json_decode($rawData, true); // 转换为关联数组
  2. 业务逻辑处理
    根据接收到的数据执行操作(如验证用户)。

    $username = $data['username'];
    $password = $data['password'];
    // 假设验证成功
    $response = ["status" => "success", "message" => "Login successful"];
    echo json_encode($response);
  3. 返回JSON响应
    设置响应头为application/json,并输出JSON数据。

    header('HTTP/1.1 200 OK');
    echo json_encode($response);

安卓端接收并解析JSON响应

  1. 读取输入流
    HttpURLConnection的输入流中读取服务器返回的数据。

    // 读取响应
    InputStream is = conn.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    StringBuilder response = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        response.append(line);
    }
  2. 解析JSON数据
    使用JSONObject或Gson解析响应。

    // 解析JSON响应
    try {
        JSONObject jsonResponse = new JSONObject(response.toString());
        String status = jsonResponse.getString("status");
        String message = jsonResponse.getString("message");
        // 处理结果
    } catch (JSONException e) {
        e.printStackTrace();
    }

错误处理与异常捕获

场景 解决方案
网络连接超时 设置conn.setConnectTimeout(5000)conn.setReadTimeout(5000)(单位:毫秒)。
JSON解析失败 使用try-catch包裹解析逻辑,检查服务器返回的格式。
服务器返回错误码 检查conn.getResponseCode(),非200时读取错误流conn.getErrorStream()

HttpURLConnection与OkHttp对比

特性 HttpURLConnection OkHttp
线程安全 需手动同步 内置线程安全
复杂度 代码冗长,需手动管理连接 链式调用,简洁高效
功能扩展 依赖原生API,扩展性低 支持拦截器、缓存等高级功能
示例代码 conn.setRequestProperty(...) RequestBody + OkHttpClient

相关问题与解答

问题1:PHP服务器是否需要处理CORS(跨域)问题?
答:不需要,CORS是浏览器对前端JavaScript的限制,而安卓应用直接通过HTTP请求与服务器通信,不涉及浏览器同源策略,因此无需处理CORS。

问题2:如何保证JSON数据传输的安全性?
答:

  1. HTTPS加密:确保通信协议为HTTPS,防止数据被窃听。
  2. 数据签名:在JSON中加入时间戳或签名字段,服务器验证后处理。
  3. 参数校验:服务器端严格校验JSON字段,避免注入攻击
0