我的android servlet旨在通过Apache Tomcat服务器上的tomcat servlet发布请求和接收响应。为了进行调试,我使用相同的POST和GET方法设置了Servlet,这样我就可以通过浏览器尝试功能和可访问性。
简而言之:当我部署应用程序时,我可以通过10.0.2.2:8080/my_app?request=test
轻松地从AVD设备浏览器访问它,我得到的结果很好。使用localhost:8080/my_app?request=test.
从我的机器访问也是如此
但是当我从我的应用程序中尝试它时,我总是得到java.io.FileNotFoundException: http://10.0.2.2:8080/my_app
。
为什么呢?
到目前为止我尝试了什么:该应用程序具有互联网权限,并且它们也可以工作,为了进入Servlet通信点,我必须首先通过PHP进行登录程序,并且它位于同一台服务器上并且正常工作
我连接到servlet的AsyncTask
如下所示:
AsyncTask<Void,Void,String> getDBdata = new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
URL url = null;
try {
url = new URL("http://10.0.2.2:8080/my_app");
} catch (MalformedURLException e) {
e.printStackTrace();
}
String text;
text = null;
JsonArray js = null;
try {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("action", "getDBData");
connection.setDoInput(true);
connection.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder builder = new StringBuilder();
String aux = "";
while ((aux = in.readLine()) != null) {
builder.append(aux);
}
text = builder.toString();
} catch (IOException e) {
e.printStackTrace();
}
return text;
答案 0 :(得分:2)
好吧,当然我一直试图在标题中发送参数,这导致了BS。菜鸟错误!
来自this question的回答帮助了我很多调试!另外,从servlet看一下服务器协议可能会让我更早地发现错误。
这是最终有效的代码:
AsyncTask<Void,Void,String> getDBdata = new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
URL url = null;
try {
url = new URL(Constants.SERVER_URL + getDBdataURL);
} catch (MalformedURLException e) {
e.printStackTrace();
}
String text;
text = null;
try {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
connection.setRequestProperty("Accept", "*/*");
connection.setChunkedStreamingMode(0);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setDoOutput(true);
connection.setRequestMethod("POST");
String request = "action=getDBdata";
PrintWriter pw = new PrintWriter(connection.getOutputStream());
pw.print(request);
pw.close();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder builder = new StringBuilder();
String aux = "";
while ((aux = in.readLine()) != null) {
builder.append(aux);
}
text = builder.toString();
} catch (IOException e) {
e.printStackTrace();
}
return text;
}