【发布时间】:2015-03-30 21:01:32
【问题描述】:
我对 java 还是有点陌生,我遇到的问题是在访问 api 的应用程序中处理错误响应。我知道在 .NET 中您可以阅读错误响应的代码、内部异常和其他详细信息,但不确定在 java 中如何执行此操作。举以下例子:我正在向 facebook graph 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
我需要使用错误代码捕获实际响应,以便正确处理异常和用户响应。任何建议表示赞赏。
【问题讨论】:
-
使用应该使用
HttpsUrlConnection,因为您使用的是https页面 -
谢谢。我试过了,但仍然无法访问消息的详细信息。
标签: java facebook-graph-api httpurlconnection