2011-04-19 156 views
0

我想測試我在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...");   
     } 
    } 

然而,當執行時,我得到它的「壞後」

+1

請檢查下面的答案。但作爲旁註,我強烈建議您使用自己的計算機(localhost)作爲服務器來學習它。您可以比每次部署 – Aleadam 2011-04-19 19:31:44

+0

時更快地修改您的代碼,這裏列出了用於調試您的http請求的工具。 http://stackoverflow.com/questions/1087185/http-testing-tool-easily-send-post-get-put – systempuntoout 2011-04-19 19:36:41

+0

你有沒有嘗試過使用標準的HTML表單提交給應用程序?這將更容易確定錯誤的位置。此外,「我知道這是一個'不好的帖子'」不是一個堆棧跟蹤。 – 2011-04-21 02:37:40

回答

2

通常你會想將它發送到特定鏈接,所以你有一種分離不同的servlet類的方法。假設doPost()方法位於myapp包中的MyAppLinkServlet類中,您將需要一個如下所示的文件web.xml來描述如何響應鏈接。順便說一句,該代碼僅稍微從GAE/J例子在http://code.google.com/appengine/docs/java/gettingstarted/creating.html

<?xml version="1.0" encoding="utf-8"?> 
<!DOCTYPE web-app PUBLIC 
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 
"http://java.sun.com/dtd/web-app_2_3.dtd"> 

<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5"> 
    <servlet> 
     <servlet-name>myapplink</servlet-name> 
     <servlet-class>myapp.MyAppLinkServlet</servlet-class> 
    </servlet> 
    <servlet-mapping> 
     <servlet-name>myapplink</servlet-name> 
     <url-pattern>/myapplink</url-pattern> 
    </servlet-mapping> 
    <welcome-file-list> 
     <welcome-file>index.html</welcome-file> 
    </welcome-file-list> 
</web-app> 

改性在服務器上,嘗試添加線

response.setStatus(200); 

(其有效地設置爲「OK」的狀態)。

在客戶端,嘗試一些簡單的入手,如:

import java.io.ByteArrayOutputStream; 
import java.io.DataOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.net.HttpURLConnection; 
import java.net.URL; 

public class TestRequest { 
    public static void main(String[] args) throws IOException { 
     String urlParameters = "action=getGroups&username=homer.simpson"; 
     String request = "http://myapp.appspot.com/myapplink"; 

     URL postUrl = new URL (request+"?"+urlParameters); 
     System.out.println(readFromUrl(postUrl)); 
    } 
    private static String readFromUrl (URL url) throws IOException { 
     FetchOptions opt = FetchOptions.Builder.doNotValidateCertificate(); //depending on how did you install GAE, you might not need this anymore 
     HTTPRequest request = new HTTPRequest (url, HTTPMethod.POST, opt); 
     URLFetchService service = URLFetchServiceFactory.getURLFetchService(); 
     HTTPResponse response = service.fetch(request); 
     if (response.getResponseCode() == HttpURLConnection.HTTP_OK) { 
     byte[] content = response.getContent(); 
      return new String(content); 
     } else { 
      return null; 
     } 
    } 
} 

祝你好運!

+0

謝謝我確保web.xml文件中的所有內容都很酷,並且更深入地閱讀它的內容。您的評論對於服務器如何響應也很有見地。我編輯了我原來的帖子,以包含我運行的測試程序,當在鏈接上聯繫服務器時失敗。任何與我的測試方法代碼看起來不對的東西,還是服務器端沒有被關注的東西? – mcorley 2011-04-19 21:05:46

+0

@mcorley我使用GAE API擴展了這個例子。我建議你唯一的另一件事是刪除所有不相關的代碼(例如用戶和組),直到你知道你有一個很好的工作響應。該代碼中的任何錯誤都會以「Bad post ...」日誌結尾。您可以稍後添加。 – Aleadam 2011-04-20 02:14:24

相關問題