0
我有一些GAE中的servlet,從Android應用中調用;我想從這些servlet之一發送POST請求到使用xampp在本地主機上託管的php。嘗試讀取響應時,servlet會發生IOException。從谷歌應用引擎發送POST請求到一個PHP
這是我使用的是樣本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只是試圖發送一個POST請求到php文件,但是在「// Response」部分中出現IOException。我想我做錯了什麼,因爲如果我從servlet複製相同的代碼並將其粘貼到Android應用程序中,而不是上面的代碼,它可以正常工作。
我應該以不同的方式在Google App Engine中執行此操作嗎?