我有带servlet的Java服务器(在NetBeans 8附带的Glassfish 4.1上运行)。我有一个在物理设备上运行的Android应用程序(API 19)(Prestigio Grace)。
servlet通过以JSON格式发回一些数据来响应GET(和POST)请求。如果我从浏览器(FF 40.0.2)发出请求(当服务器正在运行时)它工作正常。如果我从我的Android应用程序(使用相同的URL)执行相同的请求,我会获得状态代码505。
执行GET请求的Android应用中的代码:
public String makeHttpGetRequest(String urlStr) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
if (responseCode == 200) {
InputStreamReader isr = new InputStreamReader(con.getInputStream());
String response = readUntilEndOfStream(isr);
isr.close();
return response;
} else {
throw new IOException("bad status code : " + responseCode + " , from: " + urlStr);
}
}
我在servlet中使用的代码:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
handleRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
handleRequest(request, response);
}
private void handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
try {
UniversalAddress adr = params2UniversalAddress(request.getParameterMap());
AvgPricesRenovationState avgPrices = db.getAvgPricesAndRenovationState(adr);
if (avgPrices == null) { //prices for that address are not stored. Now we have to calculate them from scratch
avgPrices = getNewAvgPrices(adr);
}
response.getWriter().write(avgPrices.toHttpParams());
} catch (NullPointerException ex) {
printMissingParametersResponse(request, response);
}
}
为什么我会获取状态代码505以及如何解决此问题?