2016-01-13 296 views
1

我正在嘗試訪問Web服務。它與Android 4.4或Android 5.X工作正常。但當我試圖打「http://inmotion-prod.cloudapp.net:145/service1.svc/json/GetCustomerUUID"使用android 4.1.1它總是返回我307狀態碼,但這個網址與Android 4.4或5.x工作正常我也試圖打其他網址它在Android 4.1上工作正常0.1。 所以請告訴我是什麼問題HttpConnectionUrl總是返回狀態碼307

Log.i(TAG, url); 
     String response = null; 
     HttpURLConnection conn = null; 
     try { 
      URL webServiceUrl = new URL(url); 
      conn = (HttpURLConnection) webServiceUrl 
        .openConnection(); 
      Log.i(TAG, "Connection open"); 
      conn.setRequestMethod(GET); 
      conn.setConnectTimeout(CONNECTION_TIME_OUT); 
      conn.setRequestProperty(CONTENT_TYPE, contentType); 
      conn.setRequestProperty(ACCEPT_TYPE, acceptType); 
      conn.setDoInput(true); 
      conn.connect(); 
      Log.i(TAG, "Connection Connected"); 

      if (conn.getResponseCode() == HttpURLConnection.HTTP_OK && conn.getInputStream() != null) { 
       response = StreamUtility.convertStreamToString(conn.getInputStream()); 
       conn.getInputStream().close(); 
      } 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      if (conn != null) { 
       conn.disconnect(); 
      } 
     } 

     return response; 
    } 
+1

這是因爲頭髮生檢查一次你的代碼在這裏: - conn.setRequestProperty(TOKEN,header);確保你傳遞給在API客戶端 – Ajinkya

+0

中確認的webservices,我沒有在這裏傳遞任何標題 –

+0

Dude,「conn」的所有設置操作都被視爲標題。首先,檢查REST API客戶端中的Web服務,然後實現代碼。 – Ajinkya

回答

2

http://inmotion-prod.cloudapp.net:145/service1.svc/json/GetCustomerUUID/更換你的URL地址(末尾註意/)響應代碼將200


更新:

根據您當前的URL地址(http://inmotion-prod.cloudapp.net:145/service1.svc/json/GetCustomerUUID),而不/末,你可以使用下面的代碼:

String address = "http://inmotion-prod.cloudapp.net:145/service1.svc/json/GetCustomerUUID"; 
URL url = new URL(address); 
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 
urlConnection.setInstanceFollowRedirects(false); 
// if print out (debug or logging), you will see secondURL has/at the end 
URL secondURL = new URL(urlConnection.getHeaderField("Location")); 
HttpURLConnection urlConnection1 = (HttpURLConnection) secondURL.openConnection(); 

然後使用urlConnection1.getResponseCode()

希望它能幫助!

+0

一個非常惱人的行爲(bug?)。感謝這個代碼。很棒 – AndyB

0

BNK的答案幫助,我固定它這樣使得它也適用於較新的設備(Location頭返回爲空/空!)

String headerLocation = httpsUrlConnection.getHeaderField("Location"); 
logger.debug("Location header: " + headerLocation); 

// if the redirect URL ends with a "/" sign, but the original URL does not, it's probably the redirect bug 
String originalURL = url.toString(); 
if (!TextUtils.isEmpty(headerLocation) && headerLocation.endsWith("/") && !originalURL.endsWith("/")) 
    { 
    logger.info("Redirect Location differs from original URL, create new connection to: " + headerLocation); 
    httpsUrlConnection = (HttpsURLConnection) new URL(headerLocation).openConnection(); 

    // optional 
    httpsUrlConnection.setSSLSocketFactory(sslSocketFactory); 
    }