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

Android Studio中使用Volley获取返回纯字符串的API数据失败求助

解决Volley请求纯字符串API的问题

嘿,我知道问题出在哪了!你用的JsonObjectRequest是专门用来解析JSON对象/数组格式响应的,但这个API返回的是纯字符串(非JSON结构),比如示例里的339,Volley尝试把它当成JSON对象解析时自然会失败,触发错误回调。

最直接的解决办法是改用StringRequest——Volley专门为纯文本响应设计的请求类,修改后的代码如下:

String link = "https://uhunt.onlinejudge.org/api/uname2uid/felix_halim";
Log.d("tttt", link);

// 用StringRequest替代JsonObjectRequest
StringRequest request = new StringRequest(Request.Method.GET, link,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                // 这里直接拿到API返回的纯字符串,比如"339"
                Log.d("tttt", "获取到的用户ID: " + response);
                // 如果需要转成整数使用,记得处理格式异常
                try {
                    int userId = Integer.parseInt(response);
                    // 后续用userId做逻辑处理
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    Log.d("tttt", "用户ID格式错误");
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                Log.d("tttt", "请求出错: " + (error.getMessage() != null ? error.getMessage() : "未知错误"));
            }
});

// 别忘了把请求加入Volley的请求队列(如果之前没初始化队列的话)
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);

另外还要检查两个关键点:

  • 确保你的AndroidManifest.xml里已经添加了网络权限:
    <uses-permission android:name="android.permission.INTERNET" />
    
  • 如果API返回的字符串可能为空或非数字,一定要做好异常处理,避免崩溃。

内容的提问来源于stack exchange,提问作者Farid Chowdhury

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:05:29