2012-07-21 128 views
1

我正在製作一個android應用程序,它將使用xauth身份驗證連接到Web服務器。我的問題是,如果服務器返回401導致Java異常,我無法得到響應。java android HttpURLConnection如何獲得響應401

我需要這個迴應來知道我做錯了什麼。

首先,HttpURLConnection對這類東西有好處 其次,我怎樣才能得到響應呢?

URL u_rl = new URL(url); 
    final HttpURLConnection connection = 
     (HttpURLConnection) u_rl.openConnection(); 

    connection.setRequestMethod(method); 

    if (authorization != null) { 
     connection.setRequestProperty("Authorization", authorization); 
    } 
    final byte[] body = parameters.getBytes(); 

     connection.setRequestProperty(
      "Content-Length", Integer.toString(body.length)); 
     connection.setDoOutput(true); 
     connection.connect(); 
     final OutputStream output = connection.getOutputStream(); 
     output.write(body); 
     output.flush(); 
     System.out.println(connection.getResponseCode()); 
     if (connection.getResponseCode() != 200) { 
      result.put("error", connection.getResponseCode()+""); 
      return null; 
     } 

     String out = IOUtils.toString(connection.getInputStream()); 

我知道爲什麼我得到400或其他響應代碼,問題是用戶不知道爲什麼。服務器返回JSON中的錯誤,即使響應代碼不是200,我也想獲取該JSON代碼

+0

你必須張貼位的代碼? – SALMAN 2012-07-21 16:47:38

+0

如果我的下面的答案可以幫助你,請接受我的答案,並投票給我,這將非常感激。謝謝:) – SALMAN 2012-07-21 18:45:54

+0

張貼的代碼,但它沒有任何共同的問題,我想? – buliq 2012-07-23 17:39:54

回答

2

除非您提供它,否則很難告訴您代碼中的錯誤我寧願建議您使用這個答案肯定會幫助你。

InputStream retrieveStream(String url) { 

     DefaultHttpClient client = new DefaultHttpClient(); 

     HttpGet getRequest = new HttpGet(url); 

     try { 

      HttpResponse getResponse = client.execute(getRequest); 
      final int statusCode = getResponse.getStatusLine().getStatusCode(); 

      if (statusCode != HttpStatus.SC_OK) { 
       Log.w(getClass().getSimpleName(), "Error " + statusCode 
         + " for URL " + url); 
       return null; 
      } 

      HttpEntity getResponseEntity = getResponse.getEntity(); 
      return getResponseEntity.getContent(); 

     } catch (IOException e) { 
      getRequest.abort(); 
      Log.w(getClass().getSimpleName(), "Error for URL " + url, e); 
     } 

     return null; 

    } 

並使用此代碼將inputstream轉換爲字符串可讀的數據格式。

BufferedReader r = new BufferedReader(new InputStreamReader(retrieveStream("YOU URL"))); 
StringBuilder total = new StringBuilder(); 
String line; 
while ((line = r.readLine()) != null) { 
    total.append(line); 
} 

謝謝:)

+0

它不解決我的問題,因爲: if(statusCode!= HttpStatus.SC_OK){Log.w(getClass()。getSimpleName(),「Error」+ statusCode +「for URL」+ url);返回null;} 我仍然無法從服務器獲取JSON響應 – buliq 2012-07-23 17:40:55

+0

您能否提供您正在訪問的URL?謝謝:) – SALMAN 2012-07-23 18:00:11

+0

https://www.ankietka.pl/api/xauth/access-token – buliq 2012-07-23 20:07:37

相關問題