我想測試我在GAE上部署的服務器,以查看是否可以通過HTTP POST請求進行連接。最終客戶端將運行在Android上,但現在我想在我的筆記本電腦上運行一個簡單的測試。部署在Google App Engine上的測試服務器
我發送不同的「操作」參數作爲對服務器的請求的一部分,並基於它將查找和處理其他參數以完成請求的操作。以下是如何處理命令的示例。一個參數是動作,另一個是用戶名。它最終會返回一個JSON對象與這個用戶所屬的組,但現在我只想得到測試字符串「只是一個測試」,看看一切正常。
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
.
.
.
.
/*
* GET GROUPS
*
* @param action == getGroups
* @param user == the username of the user making the request
*/
else if(request.getParameter("action").equals("getGroups")) {
/* Query for the User by username */
User user = queryUser(request.getParameter("user"), pm);
/* Generate the list of groups this user belongs to */
ArrayList<Group> groups = null;
if(user != null) {
groups = new ArrayList<Group>(user.groups().size());
for(Group group : user.groups())
groups.add(group);
}
/* Send response back to the client */
response.setContentType("text/plain");
response.getWriter().write("Just a test");
}
A面的問題,做我發送HTTP POST請求http://myapp.appspot.com/myapplink 或者只是http://myapp.appspot.com/?
我在編寫客戶端服務器代碼時經驗不足,所以我一直在尋找使用提供的參數尋找幫助和簡單POST請求的示例,然後讀取響應(在我的示例中爲測試字符串)並將其顯示到終端。
下面是測試我跑的樣本:
public static void main(String[] args) throws IOException {
String urlParameters = "action=getGroups&username=homer.simpson";
String request = "http://myapp.appspot.com/myapplink";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setUseCaches (false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK){
System.out.println("Posted ok!");
System.out.println("Res" + connection.getResponseMessage()); //OK read
System.out.println("Size: "+connection.getContentLength()); // is 0
System.out.println("RespCode: "+connection.getResponseCode()); // is 200
System.out.println("RespMsg: "+connection.getResponseMessage()); // is 'OK'
}
else {
System.out.println("Bad post...");
}
}
然而,當執行時,我得到它的「壞後」
請檢查下面的答案。但作爲旁註,我強烈建議您使用自己的計算機(localhost)作爲服務器來學習它。您可以比每次部署 – Aleadam 2011-04-19 19:31:44
時更快地修改您的代碼,這裏列出了用於調試您的http請求的工具。 http://stackoverflow.com/questions/1087185/http-testing-tool-easily-send-post-get-put – systempuntoout 2011-04-19 19:36:41
你有沒有嘗試過使用標準的HTML表單提交給應用程序?這將更容易確定錯誤的位置。此外,「我知道這是一個'不好的帖子'」不是一個堆棧跟蹤。 – 2011-04-21 02:37:40