调用Instagram API返回内容无法解析为JSON,Volley报JSONException错误
错误原因
- 你当前使用的
https://www.instagram.com/pr.rezaabiri/?__a=1属于Instagram未公开的非正式接口,目前平台已经对这类接口做了未登录访问限制,未携带有效授权信息的请求会被直接拦截,返回HTML格式的登录页面,而不是预期的JSON数据。报错信息里的Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject就是因为返回内容是HTML页面的Doctype声明,无法被解析为JSONObject。 - 你的Volley请求没有携带Instagram要求的必要请求头,比如有效Cookie、X-IG-App-ID、符合要求的User-Agent等,触发了平台的反爬机制,返回了非JSON的拦截页面。
解决方法
- 给请求补充完整的请求头:你可以先在浏览器端登录Instagram账号,访问目标接口拿到正常返回结果后,复制该请求对应的
User-Agent、请求Cookie、X-IG-App-ID等头信息,添加到你的Volley JsonObjectRequest的请求头中。注意获取的Cookie存在有效期,过期后需要重新获取更新。
给Volley请求加头的示例代码如下:JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, response -> { try { JSONObject graphql = response.getJSONObject("graphql"); JSONObject user = graphql.getJSONObject("user"); JSONObject edge_followed_by = user.getJSONObject("edge_followed_by"); JSONObject edge_follow = user.getJSONObject("edge_follow"); JSONObject edge_owner_to_timeline_media = user.getJSONObject("edge_owner_to_timeline_media"); posts.setText(edge_owner_to_timeline_media.getString("count")); followers.setText(edge_followed_by.getString("count")); following.setText(edge_follow.getString("count")); txtAc.setText(user.getString("username")); Picasso.get().load(user.getString("profile_pic_url_hd")).into(imageProfile); } catch (JSONException e) { e.printStackTrace(); } }, error -> Log.e("err:", error.toString())) { @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> headers = new HashMap<>(); headers.put("User-Agent", "你从浏览器复制的实际UA值"); headers.put("Cookie", "你从浏览器复制的有效Cookie值"); headers.put("X-IG-App-ID", "你从浏览器复制的IG App ID值"); headers.put("X-Requested-With", "XMLHttpRequest"); return headers; } }; jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(5000, 1, 1)); Volley.newRequestQueue(getApplicationContext()).add(jsonObjectRequest); - 长期使用建议改用Meta官方提供的Instagram Graph API,走正规的OAuth2.0授权流程获取用户数据,官方接口稳定性有保障,不会出现非正式接口随时调整规则导致不可用的问题。
- 调试阶段可以先将JsonObjectRequest替换为StringRequest,先打印完整的响应内容确认返回结果格式,确认拿到正确的JSON后再做解析操作,方便快速定位问题。
内容的提问来源于stack exchange,提问作者Reza Abiri
相关产品推荐
相关产品推荐

