开发者

Testing server deployed on Google App Engine

I want to test a server I have deployed on GAE to see if a connection can be made via a HTTP POST request. The end client will run on Android but for now I would like to run a simple test on my laptop.

I send different "action" params as part of the request to the server and based on the action it will look for and handle other params to complete the request. Below is an example of how a command is handled. One param is the action and the other a username. It will in the end return a JSON object with the groups this user is a member of but for now I want to just get the test string "Just a test" back to see everything is working.

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 side question, do I send HTTP POST requests to http://myapp.appspot.com/myapplink or just to http://myapp.appspot.com/?

I have low experience writing client-server code so I was looking for help and examples of a simple POST request using supplied params and then reading the response back (with in my example the test string) and display it to the terminal.

Here is a sample of a test I was running:

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: "+connecti开发者_开发问答on.getResponseCode()); // is 200
                System.out.println("RespMsg: "+connection.getResponseMessage()); // is 'OK'
        }

        else {
            System.out.println("Bad post...");          
        } 
    }

When executing however, I get that it's a "bad post"


Usually you will want to send it to a particular link, so you have a way of separating the different servlet classes. Assuming that the doPost() method is inside MyAppLinkServlet class in the package myapp, you will need a web.xml file like the one below to describe how you will respond to the link. BTW, the code is only slightly modified from the GAE/J example at 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>

On the server, try adding the line

response.setStatus(200);

(which effectively sets the status as "OK").

On the client side, try something simple to start, such as:

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;
        }
    }
}

Good luck!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜