我们使用 Asynctask 在Android上开发了一个应用程序,用于从后端检索数据,该数据运行良好。然后,该应用程序已移至另一个新服务器。在此之后,大部分时间当我们尝试连接到服务器时,我们收到 307 (临时重定向)HTTP错误。虽然我们拥有为iOS开发的相同应用程序,但它在新服务器上运行良好。
目前,我尝试使用旧服务器的URL运行Android应用程序,它运行良好。与此同时,当我使用新服务器的URL时,问题仍然存在。
所以我需要知道它是服务器配置的问题,还是我正在使用的连接库的问题。
public void getData(MainModel mainModel) {
this.mainModel = mainModel;
requestURL = " ........";
postString = "........";
execute();
}
public HttpURLConnection POSTConnection(String postString) {
URL url = null;
HttpURLConnection httpURLConnection = null;
try {
url = new URL(requestURL);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
PrintWriter out = new PrintWriter(httpURLConnection.getOutputStream());
out.print(postString);
out.close();
} catch (MalformedURLException e) {
exception(e);
} catch (ProtocolException e) {
exception(e);
} catch (IOException e) {
exception(e);
}
return httpURLConnection;
}
public String JSONResponse(HttpURLConnection httpURLConnection) {
int statusCode = 0;
StringBuilder response;
byte[] data = null;
String responseString = null;
try {
statusCode = httpURLConnection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_OK) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader
(httpURLConnection.getInputStream()));
response = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
response.append(line);
}
data = response.toString().getBytes();
responseString = new String(data);
} else {
POSTConnection(postString);
data = null;
}
} catch (IOException e) {
exception(e);
}
return responseString;
}
protected ArrayList<....Model> doInBackground(Void... params) {
ArrayList<.....Model> myList = null;
HttpURLConnection httpURLConnection = POSTConnection(postString);
if (httpURLConnection != null) {
String responseString = JSONResponse(httpURLConnection);
if (responseString != null) {
myList = parseJSONResponse(responseString);
}
httpURLConnection.disconnect();
}
return .......;
}
提前致谢。
答案 0 :(得分:0)
查看HttpURLConnection.setFollowRedirects(boolean)方法
您应该可以在代码中添加以下内容:
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setFollowRedirects(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");