2015-03-30 75 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 
相關問題