我正在尝试点击网络服务。它与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下工作正常。我也尝试打其他网址它在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;
}
答案 0 :(得分:2)
将您的网址替换为http://inmotion-prod.cloudapp.net:145/service1.svc/json/GetCustomerUUID/
(请注意最后的/
)。响应代码为200
。
<强>更新强>
使用最后没有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()
希望它有所帮助!
答案 1 :(得分:0)
BNK的回答有所帮助,我修复了这个问题,以便它也适用于较新的设备(位置标题返回为null / empty!)
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);
}