HttpConnectionUrl 总是 return 状态码 307

HttpConnectionUrl always return status code 307

我正在尝试访问网络服务。它在 android 4.4 或 android 5.X 上运行良好。但是当我试图使用 android 4.1.1 来点击“http://inmotion-prod.cloudapp.net:145/service1.svc/json/GetCustomerUUID" 它总是返回我 307 状态代码。但是这个 url 在 android 4.4 或 5.x。我也试过打其他 url 它在 android 4.1.1 上工作正常。 所以请告诉我问题是什么

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;
    }

把你的URL地址换成http://inmotion-prod.cloudapp.net:145/service1.svc/json/GetCustomerUUID/(注意最后的/)。响应代码将为 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()

希望对您有所帮助!

BNK 的回答很有帮助,我这样修复它以便它也适用于较新的设备(位置 header 返回为空/空!)

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);
    }