1

因此,我将通过 iphone 连接到一个 servlet 并使用 HTTP。我实际上正在开发一个多人游戏,并且想知道如何通过 java (doGet) 中的 HTTP get 将特定数据发送到 iphone。我在 iphone (cocos2d-x) 上使用 libcurl。

这是我的代码的设置方式:

size_t write_data(void* buffer, size_t size, size_t nmemb, void *data)
{
    //do stuff with data        
}

//main or some init method
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl)
{
    char *data = "hi imma get=yeah";
    curl_easy_setopt(curl, CURLOPT_URL, "http://whatever.com");
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); 

    res = curl_easy_perform(curl);
    if(res != CURLE_OK)
    {
              CCLOG("WELP BETTER DO SOMETHING ERROR");
    }

    curl_easy_cleanup(curl);
}

那么,我想知道的是如何使用 java 中的 doGet 方法中的响应将字符串发送到上面定义的 write_function?如,我如何处理 doGet 方法中的响应参数?

doGet 方法供参考:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws    ServletException, IOException
 {
    System.out.println("GET METHOD CALLED");

 }

那么,现在我该如何处理该响应以将一些数据传递给 write_function?

谢谢,任何和所有的输入!

4

1 回答 1

1

通过使用响应的Writer,如下图所示。

protected void doGet(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException
{
    // tell response what format your output is in, we select plain text here
    response.setContentType("text/plain;charset=UTF-8");
    // ask the response object for a Writer object
    PrintWriter out = response.getWriter();
    try {
        // and use it like you would use System.out.  Only, this stuff gets sent 
        //to the client
        out.println("GET METHOD CALLED");
    } finally {
        // housekeeping: ensure that the Writer is closed when you're ready.
        out.close();
    }
}

在某些情况下,使用 Stream 会更容易。这也是可能的,但您永远不能同时打开 Writer 和 OutputStream

protected void doGet(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException
{
    response.setContentType("text/plain;charset=UTF-8");
    // ask the response object for an OutputStream object
    OutputStream os = response.getOutputStream();

    try {
        // output some stuff, here just the characters ABC
        os.write(new byte[]{65,66,67});
    } finally {            
        os.close();
    }

}

如果您想了解更多信息,网上有大量关于 servlet 的教程,包括oracle.com 上官方 Java EE 教程的 Servlet 章节

于 2012-10-20T01:22:02.140 回答