2015-03-30 78 views
2

我对java还是有点新,而我遇到的麻烦是在访问api的应用程序中处理错误响应。我知道在.NET中,你可以阅读错误响应的代码,内部异常和其他细节,但不知道在java中如何做到这一点。看看下面的例子:我正在facebook的图形API的一般要求,并没有得到一个错误的响应的情况下,预期的响应:在java中获取确切的http web响应httpurlconnection请求

 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 

Actu人响应:

{ 
    "error": { 
    "message": "(#803) Some of the aliases you requested do not 
    exist: zafdsdkdjdsfs", 
    "type": "OAuthException", 
    "code": 803 
    } 
} 

返回以下无需任何代码:

https://graph.facebook.com/zafdsdkdjdsfs 

我需要捕捉,以正确处理异常和用户响应,错误代码的实际响应。任何意见赞赏。

+0

使用时应使用'HttpsUrlConnection'因为你使用的是HTTPS网页 – TameHog 2015-03-30 21:20:43

+1

感谢。我尝试过,但消息的细节仍然无法访问。 – vbNewbie 2015-03-30 21:43:54

回答

0

您不能使用他们的用户名来请求用户数据,该用户数据不再适用于Facebook的Graph版本2.11。

基于在Facebook API文档,你需要一个访问令牌,并使用用户ID而不是用户名

graph.facebook.com/<user-id>/<resource|optional>&access_token=token 
相关问题