Android HttpConnectionUrl始终返回状态代码307
我正在尝试访问一个web服务。它在安卓4.4或安卓5.X上运行良好。但当我试图点击“Android HttpConnectionUrl始终返回状态代码307,android,httpurlconnection,httpconnection,Android,Httpurlconnection,Httpconnection,我正在尝试访问一个web服务。它在安卓4.4或安卓5.X上运行良好。但当我试图点击“http://inmotion-prod.cloudapp.net:145/service1.svc/json/GetCustomerUUID“使用android 4.1.1,它总是返回307状态码。但这个url在android 4.4或5.x上运行良好。我还试着点击其他url,它在安卓4.1.1上运行良好。 那么请告诉我问题出在哪里 Log.i(TAG, url); String respons
http://inmotion-prod.cloudapp.net:145/service1.svc/json/GetCustomerUUID“
使用android 4.1.1,它总是返回307状态码。但这个url在android 4.4或5.x上运行良好。我还试着点击其他url,它在安卓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的回答很有帮助,我这样修复了它,这样它也可以在较新的设备上工作(location header返回为null/empty!)
发生这种情况的原因是头在此处检查代码:-conn.setRequestProperty(令牌,头);确保无论传递给API clienti中确认的webservices的是什么,如果我没有传递任何头文件,那么“conn”的所有设置操作都将被视为头文件。首先,在RESTAPI客户端检查您的Web服务,然后实现代码。这是一个非常恼人的行为(bug?)。谢谢你的代码。效果很好
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);
}