我想测试我在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