我在 GAE 中有一些从 Android 应用程序调用的 servlet;我想使用 xampp 从这些 servlet 之一向 localhost 中托管的 php 发送 POST 请求。servlet 在尝试读取响应时遇到 IOException。
这是我正在使用的示例 servlet 的代码:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String result = "";
try {
URL url = new URL("http://172.25.3.50:80/tempofinito/prueba.php");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setDoInput(true);
// Send
DataOutputStream wr = new DataOutputStream (
con.getOutputStream ());
wr.writeBytes ("prueba=" + URLEncoder.encode("message","UTF-8"));
wr.flush ();
wr.close ();
// Response
InputStream is = con.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer resp = new StringBuffer();
while((line = rd.readLine()) != null) {
resp.append(line);
resp.append('\r');
}
rd.close();
result = resp.toString();
} catch (MalformedURLException e) {
result = "malformed";
} catch (IOException e) {
result = "ioexception";
}
// Sends result to Android APP
PrintWriter out = response.getWriter();
out.println(result);
}
这是php文件:
<?php
$variable = $_POST["prueba"];
echo "ESTO ES UNA PRUEBA ".$variable;
?>
这是Android代码:
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... params) {
HttpClient client = new DefaultHttpClient();
HttpPost postMethod = new HttpPost(Globals.serverURL + "/prueba");
String result = "";
try {
// Ignore this ->
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("UserName", Globals.user));
nameValuePairs.add(new BasicNameValuePair("Pass", Globals.encrypt(Globals.pass)));
nameValuePairs.add(new BasicNameValuePair("Mode", "user"));
// <-
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(postMethod);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
因此,APP 将 servlet 称为“prueba”。此 servlet 只是尝试向 php 文件发送 POST 请求,但在“//Response”部分遇到 IOException。我想我做错了什么,因为如果我从 servlet 复制相同的代码并将其粘贴到 Android APP 中,而不是上面的代码,它可以正常工作。
我应该在 Google App Engine 中以不同的方式执行此操作吗?