You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中HttpURLConnection报错Cannot evaluate okhttp.HttpUrl$Builder.toString()求助

解决java.lang.NullPointerException在HttpUrl$Builder.toString()的问题

让我们一步步排查你的问题:

1. 异步任务的逻辑错误(先解决这个明显的问题)

你在onCreate方法里启动AsyncTask后立刻判断myList == null,这必然会输出its null——因为AsyncTask是异步执行的,doInBackground还没来得及完成网络请求并返回结果,onPostExecute也还没给myList赋值。

修复方案:把判断myList的代码移到onPostExecute里,只有当异步任务完成后再处理结果:

@Override
protected void onPostExecute(List<Client> clients) {
    super.onPostExecute(clients);
    myList = clients;
    // 在这里判断结果
    if(myList == null) Log.v("Tag", "its null"); else Log.v("Tag", "it works");
}

2. URL拼接错误导致的NullPointerException

错误信息java.lang.NullPointerException. Cannot evaluate com.android.okhttp.HttpUrl$Builder.toString()指向URL构建失败,大概率是你拼接的WEB_URL + "Client.php"生成了无效的URL。常见原因包括:

  • WEB_URL没有http://或https://前缀
  • WEB_URL结尾没有/,导致拼接后变成http://yourdomainClient.php(缺少斜杠)
  • WEB_URL本身是null

修复方案:

  • 先打印拼接后的完整URL,确认格式正确:
    String fullUrl = WEB_URL + "Client.php";
    Log.d("URL_CHECK", "Full URL: " + fullUrl);
    String str = PHPtools.GET(fullUrl);
    
  • 确保WEB_URL以/结尾,或者拼接时手动加上:
    // 比如WEB_URL是"http://yourdomain.com/api",改成"http://yourdomain.com/api/"
    // 或者拼接时写WEB_URL + "/Client.php"
    String str = PHPtools.GET(WEB_URL + "/Client.php");
    
  • 确认WEB_URL是有效的非空字符串,没有拼写错误。

3. 补充:HttpURLConnection的异常处理优化

在你的GET方法里,最好在调用con.getResponseCode()前先检查连接是否正常,避免空指针:

public static String GET(String url) throws Exception {
    if (url == null || url.isEmpty()) {
        throw new IllegalArgumentException("URL cannot be null or empty");
    }
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("GET");
    // 先检查con是否为null
    if (con != null && con.getResponseCode() == HttpURLConnection.HTTP_OK) { 
        // 读取响应流的逻辑
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        con.disconnect(); // 记得关闭连接
        return response.toString();
    }
    // 处理非200的情况
    throw new IOException("HTTP response code: " + (con != null ? con.getResponseCode() : "unknown"));
}

按上面的步骤排查,应该能解决你的问题。

内容的提问来源于stack exchange,提问作者Or Gat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:42:52