我在GAE中有一些servlet,来自Android应用程序;我想从其中一个servlet发送一个POST请求到使用xampp在localhost中托管的php。尝试读取响应时,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中以不同的方式进行此操作吗?
答案 0 :(得分:1)
这是阻止连接的防火墙的一个愚蠢问题。