我对java仍然有点新,我遇到的问题是在访问api的应用程序中处理错误响应。我知道在.NET中你可以读取代码,内部异常和错误响应的其他细节,但在java中不确定如何执行此操作。请看以下示例:我正在向facebook图API发出一般请求,并且在发生错误响应时没有得到预期的响应:
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setRequestMethod("GET");
conn.setUseCaches(false);
conn.setRequestProperty("accept-charset", "UTF-8");
conn.setRequestProperty("content-type",
"application/x-www-form-urlencoded");
//InputStream urlInputStream = conn.getInputStream();
BufferedReader inSt = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuffer response = new StringBuffer();
String inputData;
while((inputData = inSt.readLine()) != null) {
response.append(inputData);
}
...
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
responseCode = 0;
} catch (Exception ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
responseCode = 0;
ResponseText = ex.getMessage().toString();
}
我认为printStackTrace会提供详细的错误消息和代码,但是没有,然后getMessage会在某些情况下生效。
https://graph.facebook.com/brahmaria
实际回应:
{
"error": {
"message": "Unsupported get request. Please read the
Graph API documentation at https://developers.facebook.com/docs/graph-api",
"type": "GraphMethodException",
"code": 100
}
}
上述调用将从ex.getMessage
返回错误和以下详细信息java.io.IOException: Server returned HTTP response code: 400 for
URL: https://graph.facebook.com/brahmaria
但是下一个电话不会返回详细信息:
https://graph.facebook.com/zafdsdkdjdsfs
实际回复:
{
"error": {
"message": "(#803) Some of the aliases you requested do not
exist: zafdsdkdjdsfs",
"type": "OAuthException",
"code": 803
}
}
不带任何代码返回以下内容:
https://graph.facebook.com/zafdsdkdjdsfs
我需要捕获带有错误代码的实际响应,以便正确处理异常和用户响应。任何建议表示赞赏。
答案 0 :(得分:0)
您无法使用用户名来请求用户数据,该用户名不再适用于Facebook的图表版本2.11。
基于Facebook API文档,您需要一个访问令牌并使用用户ID而不是用户名
即
graph.facebook.com/<user-id>/<resource|optional>&access_token=token